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);