diff options
author | David Tardon <dtardon@redhat.com> | 2013-04-19 18:54:16 +0200 |
---|---|---|
committer | David Tardon <dtardon@redhat.com> | 2013-04-24 05:17:10 +0000 |
commit | 6c7659b584ea7ed3652ca4eb9a2297f36310c365 (patch) | |
tree | adf631e2d3db309b0696babd9d026bce0996c215 /include/osl | |
parent | 24500d6798007d84521eb24a81c121ebe69d3bfd (diff) |
move URE headers to include/
Change-Id: Ib48a12e902f2311c295b2007f08f44dee28f431d
Reviewed-on: https://gerrit.libreoffice.org/3499
Reviewed-by: David Tardon <dtardon@redhat.com>
Tested-by: David Tardon <dtardon@redhat.com>
Diffstat (limited to 'include/osl')
32 files changed, 10161 insertions, 0 deletions
diff --git a/include/osl/conditn.h b/include/osl/conditn.h new file mode 100644 index 000000000000..8803ee85f2dd --- /dev/null +++ b/include/osl/conditn.h @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef _OSL_CONDITION_H_ +#define _OSL_CONDITION_H_ + +#include "sal/config.h" + +#include "osl/time.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* oslCondition; + +typedef enum { + osl_cond_result_ok, /* successful completion */ + osl_cond_result_error, /* error occurred, check osl_getLastSocketError() for details */ + osl_cond_result_timeout, /* blocking operation timed out */ + osl_cond_result_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslConditionResult; + +/** Creates a condition. + The condition is in the reset-state. + @returns 0 if condition could not be created. +*/ +SAL_DLLPUBLIC oslCondition SAL_CALL osl_createCondition(void); + +/** Free the memory used by the condition. + @param Condition the condition handle. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyCondition(oslCondition Condition); + +/** Sets condition to True => wait() will not block, check() returns True. + NOTE: ALL threads waiting on this condition are unblocked! + @param Condition handle to a created condition. + @return False if system-call failed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setCondition(oslCondition Condition); + +/** Sets condition to False => wait() will block, check() returns False + @param Condition handle to a created condition. + @return False if system-call failed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_resetCondition(oslCondition Condition); + +/** Blocks if condition is not set<BR> + If condition has been destroyed prematurely, wait() will + return with False. + @param Condition handle to a created condition. + @param pTimeout Tiemout value or NULL for infinite waiting + @return False if system-call failed. +*/ +SAL_DLLPUBLIC oslConditionResult SAL_CALL osl_waitCondition(oslCondition Condition, const TimeValue* pTimeout); + +/** Queries the state of the condition without blocking. + @param Condition handle to a created condition. + @return True: condition is set. <BR> + False: condition is not set. <BR> +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_checkCondition(oslCondition Condition); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_CONDITION_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/conditn.hxx b/include/osl/conditn.hxx new file mode 100644 index 000000000000..449242273a7f --- /dev/null +++ b/include/osl/conditn.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_CONDITN_HXX_ +#define _OSL_CONDITN_HXX_ + +#ifdef __cplusplus + +#include <osl/time.h> + +#include <osl/conditn.h> + + +namespace osl +{ + + class Condition + { + public: + + enum Result + { + result_ok = osl_cond_result_ok, + result_error = osl_cond_result_error, + result_timeout = osl_cond_result_timeout + }; + + /* Create a condition. + */ + Condition() + { + condition = osl_createCondition(); + } + + /* Release the OS-structures and free condition data-structure. + */ + ~Condition() + { + osl_destroyCondition(condition); + } + + /* Release all waiting threads, check returns sal_True. + */ + void set() + { + osl_setCondition(condition); + } + + /* Reset condition to false: wait() will block, check() returns sal_False. + */ + void reset() { + osl_resetCondition(condition); + } + + /** Blocks the calling thread until condition is set. + */ + Result wait(const TimeValue *pTimeout = 0) + { + return (Result) osl_waitCondition(condition, pTimeout); + } + + /** Checks if the condition is set without blocking. + */ + sal_Bool check() + { + return osl_checkCondition(condition); + } + + + private: + oslCondition condition; + + /** The underlying oslCondition has no reference count. + + Since the underlying oslCondition is not a reference counted object, copy + constructed Condition may work on an already destructed oslCondition object. + + */ + Condition(const Condition&); + + /** The underlying oslCondition has no reference count. + + When destructed, the Condition object destroys the undelying oslCondition, + which might cause severe problems in case it's a temporary object. + + */ + Condition(oslCondition condition); + + /** This assignment operator is private for the same reason as + the copy constructor. + */ + Condition& operator= (const Condition&); + + /** This assignment operator is private for the same reason as + the constructor taking a oslCondition argument. + */ + Condition& operator= (oslCondition); + }; + +} + +#endif /* __cplusplus */ +#endif /* _OSL_CONDITN_HXX_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/diagnose.h b/include/osl/diagnose.h new file mode 100644 index 000000000000..b3bfee91ad25 --- /dev/null +++ b/include/osl/diagnose.h @@ -0,0 +1,204 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef _OSL_DIAGNOSE_H_ +#define _OSL_DIAGNOSE_H_ + +#include "sal/config.h" + +#include "sal/detail/log.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +/** provides simple diagnostic support + + The facilities provided by this header are deprecated. True assertions + (that detect broken program logic) should use standard assert (which aborts + if an assertion fails, and is controlled by the standard NDEBUG macro). + Logging of warnings (e.g., about malformed input) and traces (e.g., about + steps taken while executing some protocol) should use the facilities + provided by (C++ only) sal/log.hxx. + + Because the assertion macros (OSL_ASSERT, OSL_ENSURE, OSL_FAIL, OSL_PRECOND, + and OSL_POSTCOND) have been used for true assertions as well as for logged + warnings, they map to SAL_WARN instead of standard assert. OSL_TRACE maps + to SAL_INFO. + + The functions defined in this header are not intended to be used directly, + but through defined macros. The macros can be divided into three categories: + assertions, traces and other stuff .-) Their usability depends on the value + of OSL_DEBUG_LEVEL macro: assertions are only active if OSL_DEBUG_LEVEL is 1 + or greater, traces if OSL_DEBUG_LEVEL is 2 or greater. + + Assertions (cond is bool, msg is char*): + OSL_ASSERT(cond) + If cond is false, reports an error. + + OSL_ENSURE(cond, msg) + If cond is false, reports an error with message msg. + + OSL_FAIL(msg) + Reports an error with message msg unconditionally. + + OSL_PRECOND(cond, msg) + OSL_POSTCOND(cond, msg) + These two are functionally equivalent to OSL_ENSURE(cond, msg). They are + intended to be used for checking pre- and postconditions of functions. + + Traces: + OSL_TRACE(fmt, args...) + Prints trace message. The arguments have the same meaning as the + arguments of printf. + + Other: + OSL_VERIFY(expr) + Evaluates the expression and if it is false, reports an error. The + expression is evaluated once without regard of the value of + OSL_DEBUG_LEVEL. + + Example: + + void extractBool(Any const& rAny, bool& rBool) + { + OSL_VERIFY(rAny >>= rBool); + } + + OSL_DEBUG_ONLY(expr) + */ + +#if !defined OSL_DEBUG_LEVEL +#define OSL_DEBUG_LEVEL 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* ////////////////////////////////////////////////////////////////////////// + Diagnostic support +*/ + +SAL_DLLPUBLIC void SAL_CALL osl_breakDebug(void); +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_assertFailedLine(const sal_Char* pszFileName, sal_Int32 nLine, const sal_Char* pszMessage); +SAL_DLLPUBLIC void SAL_CALL osl_trace(const sal_Char* pszFormat, ...); +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_reportError(sal_uInt32 nType, const sal_Char* pszErrorMessage); + +/* + For message delivery +*/ + +/** a message delivery function which receives a pre-formatted message string +*/ +typedef void (SAL_CALL *pfunc_osl_printDebugMessage)( const sal_Char * pszMessage ); + +/** a message delivery function which receives detailed information about where the message was triggered +*/ +typedef void (SAL_CALL *pfunc_osl_printDetailedDebugMessage)( const sal_Char * pszFileName, sal_Int32 nLine, const sal_Char* pszMessage ); + +/** sets a message delivery function + + The function set here is ignored if a function for detailed message information + (pfunc_osl_printDetailedDebugMessage) has been set. + + The given message handler must be able to cope with a null message. +*/ +SAL_DLLPUBLIC pfunc_osl_printDebugMessage SAL_CALL osl_setDebugMessageFunc( pfunc_osl_printDebugMessage pNewFunc ); + +/** sets a delivery function for detailed message information. + + The given message handler must be able to cope with a null message. +*/ +SAL_DLLPUBLIC pfunc_osl_printDetailedDebugMessage SAL_CALL osl_setDetailedDebugMessageFunc( pfunc_osl_printDetailedDebugMessage pNewFunc ); + +#ifdef __cplusplus +} +#endif + +#define OSL_THIS_FILE __FILE__ + +/* the macro OSL_LOG_PREFIX is intended to be an office internal macro for now + + it is deprecated and superseded by (C++ only) SAL_WHERE +*/ +#define OSL_LOG_PREFIX SAL_DETAIL_WHERE + +#define OSL_DEBUG_ONLY(s) _OSL_DEBUG_ONLY(s) + +#define OSL_TRACE(...) \ + SAL_DETAIL_INFO_IF_FORMAT(OSL_DEBUG_LEVEL > 0, "legacy.osl", __VA_ARGS__) + +#if OSL_DEBUG_LEVEL > 0 +#define OSL_ASSERT(c) \ + SAL_DETAIL_WARN_IF_FORMAT(!(c), "legacy.osl", "OSL_ASSERT: %s", #c) +#define OSL_ENSURE(c, m) SAL_DETAIL_WARN_IF_FORMAT(!(c), "legacy.osl", "%s", m) +#define OSL_FAIL(m) SAL_DETAIL_WARN_IF_FORMAT(sal_True, "legacy.osl", "%s", m) +#else +#define OSL_ASSERT(c) ((void) 0) +#define OSL_ENSURE(c, m) ((void) 0) +#define OSL_FAIL(m) ((void) 0) +#endif + +#define OSL_VERIFY(c) do { if (!(c)) OSL_ASSERT(0); } while (0) +#define OSL_PRECOND(c, m) OSL_ENSURE(c, m) +#define OSL_POSTCOND(c, m) OSL_ENSURE(c, m) + + +#ifdef __cplusplus +#define _OSL_GLOBAL :: +#else +#define _OSL_GLOBAL +#endif /* __cplusplus */ + +#if OSL_DEBUG_LEVEL > 0 + +#define _OSL_DEBUG_ONLY(f) (f) + +#else + +#define _OSL_DEBUG_ONLY(f) ((void)0) + +#endif /* OSL_DEBUG_LEVEL */ + +/* the macro OSL_THIS_FUNC is intended to be an office internal macro for now */ +/* copied from boost/current_function.hpp to make it usable from C + * sources as well + * + * Copyright (c) 2002 Peter Dimov and Multi Media Ltd. + * + * Distributed under the Boost Software License, Version 1.0. (See + * accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt) */ +#if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) +#define OSL_THIS_FUNC __PRETTY_FUNCTION__ +#elif defined(__DMC__) && (__DMC__ >= 0x810) +#define OSL_THIS_FUNC __PRETTY_FUNCTION__ +#elif defined(__FUNCSIG__) +#define OSL_THIS_FUNC __FUNCSIG__ +#elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) +#define OSL_THIS_FUNC __FUNCTION__ +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) +#define OSL_THIS_FUNC __func__ +#else +#define OSL_THIS_FUNC "" +#endif + +#endif /* _OSL_DIAGNOSE_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/diagnose.hxx b/include/osl/diagnose.hxx new file mode 100644 index 000000000000..bbf1fa7231c4 --- /dev/null +++ b/include/osl/diagnose.hxx @@ -0,0 +1,209 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef OSL_DIAGNOSE_HXX_INCLUDED +#define OSL_DIAGNOSE_HXX_INCLUDED + +#include "sal/config.h" + +#include <functional> +#include <typeinfo> + +#ifndef HAVE_CXX0X +#define BOOST_NO_0X_HDR_TYPEINDEX +#endif +#include "boost/unordered_set.hpp" +#include "osl/diagnose.h" +#include "osl/interlck.h" +#include "osl/mutex.hxx" +#include "rtl/allocator.hxx" +#include "rtl/instance.hxx" +#include "sal/log.hxx" +#include "sal/saldllapi.h" +#include "sal/types.h" + +/// @cond INTERNAL + +namespace osl { +namespace detail { + +struct ObjectRegistryData; + +} // namespace detail +} // namespace osl + +extern "C" { + +SAL_DLLPUBLIC bool SAL_CALL osl_detail_ObjectRegistry_storeAddresses( + char const* pName ) + SAL_THROW_EXTERN_C(); + +SAL_DLLPUBLIC bool SAL_CALL osl_detail_ObjectRegistry_checkObjectCount( + ::osl::detail::ObjectRegistryData const& rData, ::std::size_t nExpected ) + SAL_THROW_EXTERN_C(); + +SAL_DLLPUBLIC void SAL_CALL osl_detail_ObjectRegistry_registerObject( + ::osl::detail::ObjectRegistryData & rData, void const* pObj ) + SAL_THROW_EXTERN_C(); + +SAL_DLLPUBLIC void SAL_CALL osl_detail_ObjectRegistry_revokeObject( + ::osl::detail::ObjectRegistryData & rData, void const* pObj ) + SAL_THROW_EXTERN_C(); + +// These functions presumably should not be extern "C", but changing +// that would break binary compatibility. +#ifdef __clang__ +#pragma clang diagnostic push +// Guard against slightly older clang versions that don't have +// -Wreturn-type-c-linkage... +#pragma clang diagnostic ignored "-Wunknown-pragmas" +#pragma clang diagnostic ignored "-Wreturn-type-c-linkage" +#endif + +SAL_DLLPUBLIC ::osl::Mutex & SAL_CALL osl_detail_ObjectRegistry_getMutex() + SAL_THROW_EXTERN_C(); + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +} // extern "C" + +namespace osl { + +namespace detail { + +struct VoidPtrHash : ::std::unary_function<void const*, ::std::size_t> { + ::std::size_t operator()( void const* p ) const { + ::std::size_t const d = static_cast< ::std::size_t >( + reinterpret_cast< ::std::ptrdiff_t >(p) ); + return d + (d >> 3); + } +}; + +typedef ::boost::unordered_set<void const*, VoidPtrHash, ::std::equal_to<void const*>, + ::rtl::Allocator<void const*> > VoidPointerSet; + +struct ObjectRegistryData { + ObjectRegistryData( ::std::type_info const& rTypeInfo ) + : m_pName(rTypeInfo.name()), m_nCount(0), m_addresses(), + m_bStoreAddresses(osl_detail_ObjectRegistry_storeAddresses(m_pName)){} + + char const* const m_pName; + oslInterlockedCount m_nCount; + VoidPointerSet m_addresses; + bool const m_bStoreAddresses; +}; + +template <typename T> +class ObjectRegistry +{ +public: + ObjectRegistry() : m_data( typeid(T) ) {} + ~ObjectRegistry() { checkObjectCount(0); } + + bool checkObjectCount( ::std::size_t nExpected ) const { + bool const bRet = osl_detail_ObjectRegistry_checkObjectCount( + m_data, nExpected ); + if (!bRet && m_data.m_bStoreAddresses) { + MutexGuard const guard( osl_detail_ObjectRegistry_getMutex() ); + // following loop is for debugging purposes, iterating over map: + VoidPointerSet::const_iterator iPos(m_data.m_addresses.begin()); + VoidPointerSet::const_iterator const iEnd(m_data.m_addresses.end()); + for ( ; iPos != iEnd; ++iPos ) { + SAL_WARN_IF( *iPos == 0, "sal.debug", "null pointer" ); + } + } + return bRet; + } + + void registerObject( void const* pObj ) { + osl_detail_ObjectRegistry_registerObject(m_data, pObj); + } + + void revokeObject( void const* pObj ) { + osl_detail_ObjectRegistry_revokeObject(m_data, pObj); + } + +private: + // not impl: + ObjectRegistry( ObjectRegistry const& ); + ObjectRegistry const& operator=( ObjectRegistry const& ); + + ObjectRegistryData m_data; +}; + +} // namespace detail + +/** Helper class which indicates leaking object(s) of a particular class in + non-pro builds; use e.g. + + <pre> + class MyClass : private osl::DebugBase<MyClass> {...}; + </pre> + + Using the environment variable + + OSL_DEBUGBASE_STORE_ADDRESSES=MyClass;YourClass;... + + you can specify a ';'-separated list of strings matching to class names + (or "all" for all classes), for which DebugBase stores addresses to created + objects instead of just counting them. This enables you to iterate over + leaking objects in your debugger. + + @tparam InheritingClassT binds the template instance to that class + @attention Use at own risk. + For now this is just public (yet unpublished) API and may change + in the future! +*/ +template <typename InheritingClassT> +class DebugBase +{ +public: +#if OSL_DEBUG_LEVEL <= 0 + static bool checkObjectCount( ::std::size_t = 0 ) { return true; } +#else // OSL_DEBUG_LEVEL > 0 + /** @return whether the expected number of objects is alive, + else this function SAL_WARNs + */ + static bool checkObjectCount( ::std::size_t nExpected = 0 ) { + return StaticObjectRegistry::get().checkObjectCount(nExpected); + } + +protected: + DebugBase() { + StaticObjectRegistry::get().registerObject( this ); + } + ~DebugBase() { + StaticObjectRegistry::get().revokeObject( this ); + } + +private: + struct StaticObjectRegistry + : ::rtl::Static<detail::ObjectRegistry<InheritingClassT>, + StaticObjectRegistry> {}; +#endif +}; + +} // namespace osl + +/// @endcond + +#endif // ! defined(OSL_DIAGNOSE_HXX_INCLUDED) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/doublecheckedlocking.h b/include/osl/doublecheckedlocking.h new file mode 100644 index 000000000000..64b07d46cd6c --- /dev/null +++ b/include/osl/doublecheckedlocking.h @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H +#define INCLUDED_OSL_DOUBLECHECKEDLOCKING_H + +#if defined __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** A platform specific macro needed to make double-checked locking work. + + See + <http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html> + for a description of double-checked locking, why it is broken, and how it + can be fixed. On platforms where it is necessary, this macro will expand + to some memory barrier instruction. On many platforms, double-checked + locking works as it is, though, so on those platforms this macro will be + empty. This is a macro instead of a (C++ inline) function to allow for + maximum performance in both C and C++. + + If possible, use the rtl_Instance template instead of explicitly spelling + out the double-checked locking pattern. There are few cases where you + will have to spell it out explicitly (e.g., the logic of a certain + instance of the pattern is too complex to be mapped to the template, or + some compiler refuses to compile a template instantiation due to internal + compiler errors), though, and you should always call this macro at the + right places then: + + static T * pInstance = 0; + + T * p = pInstance; + if (!p) + { + Guard aGuard(aMutex); + p = pInstance; + if (!p) + { + p = ...; + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + pInstance = p; + } + } + else + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + return p; + + One extra advantage of this macro is that it makes it easier to find all + places where double-checked locking is used. + */ +#define OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER() /* empty */ + +#if defined __cplusplus +} +#endif /* __cplusplus */ + +#endif /* INCLUDED_OSL_DOUBLECHECKEDLOCKING_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/endian.h b/include/osl/endian.h new file mode 100644 index 000000000000..82ec1eaca7b1 --- /dev/null +++ b/include/osl/endian.h @@ -0,0 +1,226 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_ENDIAN_H_ +#define _OSL_ENDIAN_H_ + +#include <sal/types.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** Determine the platform byte order as _BIG_ENDIAN, _LITTLE_ENDIAN, ... + */ +#ifdef _WIN32 +# if defined(_M_IX86) +# define _LITTLE_ENDIAN +# elif defined(_M_AMD64) +# define _LITTLE_ENDIAN +# elif defined(_M_MRX000) +# define _LITTLE_ENDIAN +# elif defined(_M_ALPHA) +# define _LITTLE_ENDIAN +# elif defined(_M_PPC) +# define _LITTLE_ENDIAN +# endif +#endif + +#ifdef LINUX +# include <endian.h> +# if __BYTE_ORDER == __LITTLE_ENDIAN +# ifndef _LITTLE_ENDIAN +# define _LITTLE_ENDIAN +# endif +# elif __BYTE_ORDER == __BIG_ENDIAN +# ifndef _BIG_ENDIAN +# define _BIG_ENDIAN +# endif +# endif +#endif + +#ifdef ANDROID +# include <endian.h> +# if __BYTE_ORDER == __LITTLE_ENDIAN +# ifndef _LITTLE_ENDIAN +# define _LITTLE_ENDIAN +# endif +# elif __BYTE_ORDER == __BIG_ENDIAN +# ifndef _BIG_ENDIAN +# define _BIG_ENDIAN +# endif +# endif +#endif + +#ifdef NETBSD +# include <machine/endian.h> +# if BYTE_ORDER == LITTLE_ENDIAN +# undef _BIG_ENDIAN +# elif BYTE_ORDER == BIG_ENDIAN +# undef _LITTLE_ENDIAN +# endif +#endif + +#ifdef FREEBSD +# include <sys/param.h> +# include <machine/endian.h> +#if __FreeBSD_version < 500000 +# if BYTE_ORDER == LITTLE_ENDIAN +# define _LITTLE_ENDIAN +# elif BYTE_ORDER == BIG_ENDIAN +# define _BIG_ENDIAN +# endif +#endif +#endif + +#ifdef AIX +# include <sys/machine.h> +# if BYTE_ORDER == LITTLE_ENDIAN +# ifndef _LITTLE_ENDIAN +# define _LITTLE_ENDIAN +# endif +# elif BYTE_ORDER == BIG_ENDIAN +# ifndef _BIG_ENDIAN +# define _BIG_ENDIAN +# endif +# endif +#endif + +#ifdef SOLARIS +# include <sys/isa_defs.h> +#endif + +#ifdef MACOSX +# include <machine/endian.h> +# if BYTE_ORDER == LITTLE_ENDIAN +# ifndef _LITTLE_ENDIAN +# define _LITTLE_ENDIAN +# endif +# elif BYTE_ORDER == BIG_ENDIAN +# ifndef _BIG_ENDIAN +# define _BIG_ENDIAN +# endif +# endif +#endif + +#ifdef IOS +# include <machine/endian.h> +# if BYTE_ORDER == LITTLE_ENDIAN +# ifndef _LITTLE_ENDIAN +# define _LITTLE_ENDIAN +# endif +# elif BYTE_ORDER == BIG_ENDIAN +# ifndef _BIG_ENDIAN +# define _BIG_ENDIAN +# endif +# endif +#endif + +/** Check supported platform. + */ +#if !defined(_WIN32) && \ + !defined(LINUX) && !defined(NETBSD) && \ + !defined(AIX) && !defined(OPENBSD) && \ + !defined(SOLARIS) && !defined(MACOSX) && !defined(FREEBSD) && \ + !defined(DRAGONFLY) && \ + !defined(IOS) && !defined(ANDROID) +# error "Target platform not specified !" +#endif + + +/** Define the determined byte order as OSL_BIGENDIAN or OSL_LITENDIAN. + */ +#if defined _LITTLE_ENDIAN +# define OSL_LITENDIAN +#elif defined _BIG_ENDIAN +# define OSL_BIGENDIAN +#else +# error undetermined endianess +#endif + + +/** Define macros for byte order manipulation. + */ +#ifndef OSL_MAKEBYTE +# define OSL_MAKEBYTE(nl, nh) ((sal_uInt8)(((nl) & 0x0F) | (((nh) & 0x0F) << 4))) +#endif +#ifndef OSL_LONIBBLE +# define OSL_LONIBBLE(b) ((sal_uInt8)((b) & 0x0F)) +#endif +#ifndef OSL_HINIBBLE +# define OSL_HINIBBLE(b) ((sal_uInt8)(((b) >> 4) & 0x0F)) +#endif + +#ifndef OSL_MAKEWORD +# define OSL_MAKEWORD(bl, bh) ((sal_uInt16)((bl) & 0xFF) | (((sal_uInt16)(bh) & 0xFF) << 8)) +#endif +#ifndef OSL_LOBYTE +# define OSL_LOBYTE(w) ((sal_uInt8)((sal_uInt16)(w) & 0xFF)) +#endif +#ifndef OSL_HIBYTE +# define OSL_HIBYTE(w) ((sal_uInt8)(((sal_uInt16)(w) >> 8) & 0xFF)) +#endif + +#ifndef OSL_MAKEDWORD +# define OSL_MAKEDWORD(wl, wh) ((sal_uInt32)((wl) & 0xFFFF) | (((sal_uInt32)(wh) & 0xFFFF) << 16)) +#endif +#ifndef OSL_LOWORD +# define OSL_LOWORD(d) ((sal_uInt16)((sal_uInt32)(d) & 0xFFFF)) +#endif +#ifndef OSL_HIWORD +# define OSL_HIWORD(d) ((sal_uInt16)(((sal_uInt32)(d) >> 16) & 0xFFFF)) +#endif + + +/** Define macros for swapping between host and network byte order. + */ +#ifdef OSL_BIGENDIAN +#ifndef OSL_NETWORD +# define OSL_NETWORD(w) (sal_uInt16)(w) +#endif +#ifndef OSL_NETDWORD +# define OSL_NETDWORD(d) (sal_uInt32)(d) +#endif +#else /* OSL_LITENDIAN */ +#ifndef OSL_NETWORD +# define OSL_NETWORD(w) OSL_MAKEWORD(OSL_HIBYTE(w),OSL_LOBYTE(w)) +#endif +#ifndef OSL_NETDWORD +# define OSL_NETDWORD(d) OSL_MAKEDWORD(OSL_NETWORD(OSL_HIWORD(d)),OSL_NETWORD(OSL_LOWORD(d))) +#endif +#endif /* OSL_BIGENDIAN */ + + +/** Define macros for swapping between byte orders. + */ +#ifndef OSL_SWAPWORD +# define OSL_SWAPWORD(w) OSL_MAKEWORD(OSL_HIBYTE(w),OSL_LOBYTE(w)) +#endif +#ifndef OSL_SWAPDWORD +# define OSL_SWAPDWORD(d) OSL_MAKEDWORD(OSL_SWAPWORD(OSL_HIWORD(d)),OSL_SWAPWORD(OSL_LOWORD(d))) +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /*_OSL_ENDIAN_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/file.h b/include/osl/file.h new file mode 100644 index 000000000000..e8277e21ebc3 --- /dev/null +++ b/include/osl/file.h @@ -0,0 +1,1639 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_FILE_H_ +#define _OSL_FILE_H_ + +#include "sal/config.h" + +#include "osl/time.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @file + +Main goals and usage hints + +The main intentention of this interface is to provide an universal portable and +high performance access to file system issues on any operating system.<p> + +There are a few main goals:<p> + +1.The path specifications always has to be absolut. Any usage of relative path +specifications is forbidden. Exceptions are <code>osl_getSystemPathFromFileURL</code>, +<code>osl_getFileURLFromSystemPath</code> and <code>osl_getAbsoluteFileURL</code>. Most operating systems +provide a "Current Directory" per process. This is the reason why relative path +specifications can cause problems in multithreading environments.<p> + +2.Proprietary notations of file paths are not supported. Every path notation +must the file URL specification. File URLs must be encoded in UTF8 and +after that escaped. Although the URL parameter is a unicode string, the must +contain only ASCII characters<p> + +3.The caller cannot get any information whether a file system is case sensitive, +case preserving or not. The operating system implementation itself should +determine if it can map case-insensitive paths. The case correct notation of +a filename or file path is part of the "File Info". This case correct name +can be used as a unique key if neccessary.<p> + +4. Obtaining information about files or volumes is controlled by a +bitmask which specifies which fields are of interest. Due to performance +issues it is not recommended to obtain information which is not needed. +But if the operating system provides more information anyway the +implementation can set more fields on output as were requested. It is in the +responsibility of the caller to decide if he uses this additional information +or not. But he should do so to prevent further unnecessary calls if the information +is already there.<br> + +The input bitmask supports a flag <code>osl_FileStatus_Mask_Validate</code> which +can be used to force retrieving uncached validated information. Setting this flag +when calling <code>osl_getFileStatus</code> in combination with no other flag is +a synonym for a "FileExists". This should only be done when processing a single file +(f.e. before opening) and NEVER during enumeration of directory contents on any step +of information processing. This would change the runtime behaviour from O(n) to +O(n*n/2) on nearly every file system.<br> +On Windows NT reading the contents of an directory with 7000 entries and +getting full information about every file only takes 0.6 seconds. Specifying the +flag <code>osl_FileStatus_Mask_Validate</code> for each entry will increase the +time to 180 seconds (!!!). + +*/ + + + +/* Error codes according to errno */ + +typedef enum { + osl_File_E_None, + osl_File_E_PERM, + osl_File_E_NOENT, + osl_File_E_SRCH, + osl_File_E_INTR, + osl_File_E_IO, + osl_File_E_NXIO, + osl_File_E_2BIG, + osl_File_E_NOEXEC, + osl_File_E_BADF, + osl_File_E_CHILD, + osl_File_E_AGAIN, + osl_File_E_NOMEM, + osl_File_E_ACCES, + osl_File_E_FAULT, + osl_File_E_BUSY, + osl_File_E_EXIST, + osl_File_E_XDEV, + osl_File_E_NODEV, + osl_File_E_NOTDIR, + osl_File_E_ISDIR, + osl_File_E_INVAL, + osl_File_E_NFILE, + osl_File_E_MFILE, + osl_File_E_NOTTY, + osl_File_E_FBIG, + osl_File_E_NOSPC, + osl_File_E_SPIPE, + osl_File_E_ROFS, + osl_File_E_MLINK, + osl_File_E_PIPE, + osl_File_E_DOM, + osl_File_E_RANGE, + osl_File_E_DEADLK, + osl_File_E_NAMETOOLONG, + osl_File_E_NOLCK, + osl_File_E_NOSYS, + osl_File_E_NOTEMPTY, + osl_File_E_LOOP, + osl_File_E_ILSEQ, + osl_File_E_NOLINK, + osl_File_E_MULTIHOP, + osl_File_E_USERS, + osl_File_E_OVERFLOW, + osl_File_E_NOTREADY, + osl_File_E_invalidError, /* unmapped error: always last entry in enum! */ + osl_File_E_TIMEDOUT, + osl_File_E_NETWORK, + osl_File_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslFileError; + +typedef void *oslDirectory; +typedef void *oslDirectoryItem; + + +/** Open a directory for enumerating its contents. + + @param pustrDirectoryURL [in] + The full qualified URL of the directory. + + @param pDirectory [out] + On success it receives a handle used for subsequent calls by osl_getNextDirectoryItem(). + The handle has to be released by a call to osl_closeDirectory(). + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOENT the specified path doesn't exist<br> + osl_File_E_NOTDIR the specified path is not an directory <br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_ACCES permission denied<br> + osl_File_E_MFILE too many open files used by the process<br> + osl_File_E_NFILE too many open files in the system<br> + osl_File_E_NAMETOOLONG File name too long<br> + osl_File_E_LOOP Too many symbolic links encountered<p> + + @see osl_getNextDirectoryItem() + @see osl_closeDirectory() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_openDirectory( + rtl_uString *pustrDirectoryURL, oslDirectory *pDirectory); + + +/** Retrieve the next item of a previously opened directory. + + Retrieves the next item of a previously opened directory. + All handles have an initial refcount of 1. + + @param Directory [in] + A directory handle received from a previous call to osl_openDirectory(). + + @param pItem [out] + On success it receives a handle that can be used for subsequent calls to osl_getFileStatus(). + The handle has to be released by a call to osl_releaseDirectoryItem(). + + @param uHint [in] + With this parameter the caller can tell the implementation that (s)he + is going to call this function uHint times afterwards. This enables the implementation to + get the information for more than one file and cache it until the next calls. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_NOENT no more entries in this directory<br> + osl_File_E_BADF invalid oslDirectory parameter<br> + osl_File_E_OVERFLOW the value too large for defined data type + + @see osl_releaseDirectoryItem() + @see osl_acquireDirectoryItem() + @see osl_getDirectoryItem() + @see osl_getFileStatus() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getNextDirectoryItem( + oslDirectory Directory, + oslDirectoryItem *pItem, + sal_uInt32 uHint + ); + + +/** Release a directory handle. + + @param Directory [in] + A handle received by a call to osl_openDirectory(). + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures<br> + osl_File_E_BADF invalid oslDirectory parameter<br> + osl_File_E_INTR the function call was interrupted<p> + + @see osl_openDirectory() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_closeDirectory( + oslDirectory Directory); + + +/** Retrieve a single directory item. + + Retrieves a single directory item. The returned handle has an initial refcount of 1. + Due to performance issues it is not recommended to use this function while + enumerating the contents of a directory. In this case use osl_getNextDirectoryItem() instead. + + @param pustrFileURL [in] + An absolute file URL. + + @param pItem [out] + On success it receives a handle which can be used for subsequent calls to osl_getFileStatus(). + The handle has to be released by a call to osl_releaseDirectoryItem(). + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_ACCES permission denied<br> + osl_File_E_MFILE too many open files used by the process<br> + osl_File_E_NFILE too many open files in the system<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_NAMETOOLONG the file name is too long<br> + osl_File_E_NOTDIR a component of the path prefix of path is not a directory<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_FAULT bad address<br> + osl_File_E_INTR the function call was interrupted<p> + + @see osl_releaseDirectoryItem() + @see osl_acquireDirectoryItem() + @see osl_getFileStatus() + @see osl_getNextDirectoryItem() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getDirectoryItem( + rtl_uString *pustrFileURL, + oslDirectoryItem *pItem + ); + + +/** Increase the refcount of a directory item handle. + + The caller responsible for releasing the directory item handle using osl_releaseDirectoryItem(). + + @param Item [in] + A handle received by a call to osl_getDirectoryItem() or osl_getNextDirectoryItem(). + + @return + osl_File_E_None on success<br> + osl_File_E_NOMEM not enough memory for allocating structures<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + + @see osl_getDirectoryItem() + @see osl_getNextDirectoryItem() + @see osl_releaseDirectoryItem() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_acquireDirectoryItem( + oslDirectoryItem Item ); + + +/** Decrease the refcount of a directory item handle. + + Decreases the refcount of a directory item handle. + If the refcount reaches 0 the data associated with + this directory item handle will be released. + + @param Item [in] + A handle received by a call to osl_getDirectoryItem() or osl_getNextDirectoryItem(). + + @return + osl_File_E_None on success<br> + osl_File_E_NOMEM not enough memory for allocating structures<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + + @see osl_getDirectoryItem() + @see osl_getNextDirectoryItem() + @see osl_acquireDirectoryItem() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_releaseDirectoryItem( + oslDirectoryItem Item ); + +/** Determine if two directory items point the same underlying file + + The comparison is done first by URL, and then by resolving links to + find the target, and finally by comparing inodes on unix. + + @param pItemA [in] + A directory handle to compare with another handle + + @param pItemB [in] + A directory handle to compare with pItemA + + @return + sal_True: if the items point to an identical resource<br> + sal_False: if the items point to a different resource, or a fatal error occured<br> + + @see osl_getDirectoryItem() + + @since LibreOffice 3.6 +*/ + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_identicalDirectoryItem( + oslDirectoryItem pItemA, + oslDirectoryItem pItemB ); + +/* File types */ + +typedef enum { + osl_File_Type_Directory, + osl_File_Type_Volume, + osl_File_Type_Regular, + osl_File_Type_Fifo, + osl_File_Type_Socket, + osl_File_Type_Link, + osl_File_Type_Special, + osl_File_Type_Unknown +} oslFileType; + +/* File attributes */ +#define osl_File_Attribute_ReadOnly 0x00000001 +#define osl_File_Attribute_Hidden 0x00000002 +#define osl_File_Attribute_Executable 0x00000010 +#define osl_File_Attribute_GrpWrite 0x00000020 +#define osl_File_Attribute_GrpRead 0x00000040 +#define osl_File_Attribute_GrpExe 0x00000080 +#define osl_File_Attribute_OwnWrite 0x00000100 +#define osl_File_Attribute_OwnRead 0x00000200 +#define osl_File_Attribute_OwnExe 0x00000400 +#define osl_File_Attribute_OthWrite 0x00000800 +#define osl_File_Attribute_OthRead 0x00001000 +#define osl_File_Attribute_OthExe 0x00002000 + +/* Flags specifying which fields to retrieve by osl_getFileStatus */ + +#define osl_FileStatus_Mask_Type 0x00000001 +#define osl_FileStatus_Mask_Attributes 0x00000002 +#define osl_FileStatus_Mask_CreationTime 0x00000010 +#define osl_FileStatus_Mask_AccessTime 0x00000020 +#define osl_FileStatus_Mask_ModifyTime 0x00000040 +#define osl_FileStatus_Mask_FileSize 0x00000080 +#define osl_FileStatus_Mask_FileName 0x00000100 +#define osl_FileStatus_Mask_FileURL 0x00000200 +#define osl_FileStatus_Mask_LinkTargetURL 0x00000400 +#define osl_FileStatus_Mask_All 0x7FFFFFFF +#define osl_FileStatus_Mask_Validate 0x80000000 + + +typedef + +/** Structure containing information about files and directories + + @see osl_getFileStatus() + @see oslFileType +*/ + +struct _oslFileStatus { +/** Must be initialized with the size in bytes of the structure before passing it to any function */ + sal_uInt32 uStructSize; +/** Determines which members of the structure contain valid data */ + sal_uInt32 uValidFields; +/** The type of the file (file, directory, volume). */ + oslFileType eType; +/** File attributes */ + sal_uInt64 uAttributes; +/** First creation time in nanoseconds since 1/1/1970. Can be the last modify time depending on + platform or file system. */ + TimeValue aCreationTime; +/** Last access time in nanoseconds since 1/1/1970. Can be the last modify time depending on + platform or file system. */ + TimeValue aAccessTime; +/** Last modify time in nanoseconds since 1/1/1970. */ + TimeValue aModifyTime; +/** Size in bytes of the file. Zero for directories and volumes. */ + sal_uInt64 uFileSize; +/** Case correct name of the file. Should be set to zero before calling <code>osl_getFileStatus</code> + and released after usage. */ + rtl_uString *ustrFileName; +/** Full URL of the file. Should be set to zero before calling <code>osl_getFileStatus</code> + and released after usage. */ + rtl_uString *ustrFileURL; +/** Full URL of the target file if the file itself is a link. + Should be set to zero before calling <code>osl_getFileStatus</code> + and released after usage. */ + rtl_uString *ustrLinkTargetURL; +} oslFileStatus; + + +/** Retrieve information about a single file or directory. + + @param Item [in] + A handle received by a previous call to osl_getDirectoryItem() or osl_getNextDirectoryItem(). + + @param pStatus [in|out] + Points to a structure which receives the information of the file or directory + represented by the handle Item. The member uStructSize has to be initialized to + sizeof(oslFileStatus) before calling this function. + + @param uFieldMask [in] + Specifies which fields of the structure pointed to by pStatus are of interest to the caller. + + @return + osl_File_E_None on success<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_BADF invalid oslDirectoryItem parameter<br> + osl_File_E_FAULT bad address<br> + osl_File_E_OVERFLOW value too large for defined data type<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_MULTIHOP components of path require hopping to multiple remote machines and the file system does not allow it<br> + osl_File_E_MFILE too many open files used by the process<br> + osl_File_E_NFILE too many open files in the system<br> + osl_File_E_NOSPC no space left on device<br> + osl_File_E_NXIO no such device or address<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_NOSYS function not implemented<p> + + @see osl_getDirectoryItem() + @see osl_getNextDirectoryItem() + @see oslFileStatus +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFileStatus( + oslDirectoryItem Item, oslFileStatus *pStatus, sal_uInt32 uFieldMask ); + + +typedef void *oslVolumeDeviceHandle; + +/** Release a volume device handle. + + Releases the given oslVolumeDeviceHandle which was acquired by a call to + osl_getVolumeInformation() or osl_acquireVolumeDeviceHandle(). + + @param Handle [in] + An oslVolumeDeviceHandle received by a call to osl_getVolumeInformation(). + + @return + osl_File_E_None on success<br> + + @todo + specify all error codes that may be returned + + @see osl_acquireVolumeDeviceHandle() + @see osl_getVolumeInformation() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_releaseVolumeDeviceHandle( + oslVolumeDeviceHandle Handle ); + +/** Acquire a volume device handle. + + Acquires the given oslVolumeDeviceHandle which was acquired by a call to + osl_getVolumeInformation(). The caller is responsible for releasing the + acquired handle by calling osl_releaseVolumeDeviceHandle(). + + @param Handle [in] + An oslVolumeDeviceHandle received by a call to osl_getVolumeInformation(). + + @return + osl_File_E_None on success<br> + + @todo + specify all error codes that may be returned + + @see osl_getVolumeInformation() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_acquireVolumeDeviceHandle( + oslVolumeDeviceHandle Handle ); + + +/** Get the full qualified URL where a device is mounted to. + + @param Handle [in] + An oslVolumeDeviceHandle received by a call to osl_getVolumeInformation(). + + @param ppustrDirectoryURL [out] + Receives the full qualified URL where the device is mounted to. + + @return + osl_File_E_None on success<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_NXIO no such device or address<br> + osl_File_E_NODEV no such device<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_FAULT bad address<br> + osl_FilE_E_INTR function call was interrupted<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_EOVERFLOW value too large for defined data type<br> + + @see osl_getVolumeInformation() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getVolumeDeviceMountPath( + oslVolumeDeviceHandle Handle, rtl_uString **ppustrDirectoryURL); + +/* Volume attributes */ + +#define osl_Volume_Attribute_Removeable 0x00000001L +#define osl_Volume_Attribute_Remote 0x00000002L +#define osl_Volume_Attribute_CompactDisc 0x00000004L +#define osl_Volume_Attribute_FixedDisk 0x00000008L +#define osl_Volume_Attribute_RAMDisk 0x00000010L +#define osl_Volume_Attribute_FloppyDisk 0x00000020L + +#define osl_Volume_Attribute_Case_Is_Preserved 0x00000040L +#define osl_Volume_Attribute_Case_Sensitive 0x00000080L + +/* Flags specifying which fields to retrieve by osl_getVolumeInfo */ + +#define osl_VolumeInfo_Mask_Attributes 0x00000001L +#define osl_VolumeInfo_Mask_TotalSpace 0x00000002L +#define osl_VolumeInfo_Mask_UsedSpace 0x00000004L +#define osl_VolumeInfo_Mask_FreeSpace 0x00000008L +#define osl_VolumeInfo_Mask_MaxNameLength 0x00000010L +#define osl_VolumeInfo_Mask_MaxPathLength 0x00000020L +#define osl_VolumeInfo_Mask_FileSystemName 0x00000040L +#define osl_VolumeInfo_Mask_DeviceHandle 0x00000080L +#define osl_VolumeInfo_Mask_FileSystemCaseHandling 0x00000100L + +typedef + +/** Structure containing information about volumes + + @see osl_getVolumeInformation() + @see oslFileType +*/ + +struct _oslVolumeInfo { +/** Must be initialized with the size in bytes of the structure before passing it to any function */ + sal_uInt32 uStructSize; +/** Determines which members of the structure contain valid data */ + sal_uInt32 uValidFields; +/** Attributes of the volume (remote and/or removable) */ + sal_uInt32 uAttributes; +/** Total availiable space on the volume for the current process/user */ + sal_uInt64 uTotalSpace; +/** Used space on the volume for the current process/user */ + sal_uInt64 uUsedSpace; +/** Free space on the volume for the current process/user */ + sal_uInt64 uFreeSpace; +/** Maximum length of file name of a single item */ + sal_uInt32 uMaxNameLength; +/** Maximum length of a full quallified path in system notation */ + sal_uInt32 uMaxPathLength; +/** Points to a string that receives the name of the file system type. String should be set to zero before calling <code>osl_getVolumeInformation</code> + and released after usage. */ + rtl_uString *ustrFileSystemName; +/** Pointer to handle the receives underlying device. Handle should be set to zero before calling <code>osl_getVolumeInformation</code>*/ + oslVolumeDeviceHandle *pDeviceHandle; +} oslVolumeInfo; + + +/** Retrieve information about a volume. + + Retrieves information about a volume. A volume can either be a mount point, a network + resource or a drive depending on Operating System and File System. Before calling this + function osl_getFileStatus() should be called to determine if the type is + osl_file_Type_Volume. + + @param pustrDirectoryURL [in] + Full qualified URL of the volume + + @param pInfo [out] + On success it receives information about the volume. + + @param uFieldMask [in] + Specifies which members of the structure should be filled + + @return + osl_File_E_None on success<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOTDIR not a directory<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_LOOP too many symbolic links encountered<br> + ols_File_E_FAULT Bad address<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_NOSYS function not implemented<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_INTR function call was interrupted<br> + + @see osl_getFileStatus() + @see oslVolumeInfo +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getVolumeInformation( + rtl_uString *pustrDirectoryURL, + oslVolumeInfo *pInfo, + sal_uInt32 uFieldMask ); + +typedef void *oslFileHandle; + +/* Open flags */ + +#define osl_File_OpenFlag_Read 0x00000001L +#define osl_File_OpenFlag_Write 0x00000002L +#define osl_File_OpenFlag_Create 0x00000004L +#define osl_File_OpenFlag_NoLock 0x00000008L +/* larger bit-fields reserved for internal use cf. detail/file.h */ + +/** Open a regular file. + + Open a file. Only regular files can be openend. + + @param pustrFileURL [in] + The full qualified URL of the file to open. + + @param pHandle [out] + On success it receives a handle to the open file. + + @param uFlags [in] + Specifies the open mode. + + On Android, if the file path is below the /assets folder, the file + exists only as a hopefully uncompressed element inside the app + package (.apk), which has been mapped into memory as a whole by + the LibreOffice Android bootstrapping code. So files "opened" from + there aren't actually files in the OS sense. + + @return + osl_File_E_None on success<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NAMETOOLONG pathname was too long<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_AGAIN a write lock could not be established<br> + osl_File_E_NOTDIR not a directory<br> + osl_File_E_NXIO no such device or address<br> + osl_File_E_NODEV no such device<br> + osl_File_E_ROFS read-only file system<br> + osl_File_E_TXTBSY text file busy<br> + osl_File_E_FAULT bad address<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_NOSPC no space left on device<br> + osl_File_E_ISDIR is a directory<br> + osl_File_E_MFILE too many open files used by the process<br> + osl_File_E_NFILE too many open files in the system<br> + osl_File_E_DQUOT quota exceeded<br> + osl_File_E_EXIST file exists<br> + osl_FilE_E_INTR function call was interrupted<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_EOVERFLOW value too large for defined data type<br> + + @see osl_closeFile() + @see osl_setFilePos() + @see osl_getFilePos() + @see osl_readFile() + @see osl_writeFile() + @see osl_setFileSize() + @see osl_getFileSize() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_openFile( + rtl_uString *pustrFileURL, oslFileHandle *pHandle, sal_uInt32 uFlags ); + +#define osl_Pos_Absolut 1 +#define osl_Pos_Current 2 +#define osl_Pos_End 3 + +/** Set the internal position pointer of an open file. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param uHow [in] + Distance to move the internal position pointer (from uPos). + + @param uPos [in] + Absolute position from the beginning of the file. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files<br> + + @see osl_openFile() + @see osl_getFilePos() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFilePos( + oslFileHandle Handle, sal_uInt32 uHow, sal_Int64 uPos ) SAL_WARN_UNUSED_RESULT; + + +/** Retrieve the current position of the internal pointer of an open file. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param pPos [out] + On success receives the current position of the file pointer. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files<br> + + @see osl_openFile() + @see osl_setFilePos() + @see osl_readFile() + @see osl_writeFile() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFilePos( + oslFileHandle Handle, sal_uInt64 *pPos ); + + +/** Set the file size of an open file. + + Sets the file size of an open file. The file can be truncated or enlarged by the function. + The position of the file pointer is not affeced by this function. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param uSize [in] + New size in bytes. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files<br> + + @see osl_openFile() + @see osl_setFilePos() + @see osl_getFileStatus() + @see osl_getFileSize() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFileSize( + oslFileHandle Handle, sal_uInt64 uSize ); + + +/** Get the file size of an open file. + + Gets the file size of an open file. + The position of the file pointer is not affeced by this function. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param pSize [out] + Current size in bytes. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files<br> + + @see osl_openFile() + @see osl_setFilePos() + @see osl_getFileStatus() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFileSize( + oslFileHandle Handle, sal_uInt64 *pSize ); + + +/** Map flags. + + @since UDK 3.2.10 + */ +#define osl_File_MapFlag_RandomAccess ((sal_uInt32)(0x1)) + +/** Map flag denoting that the mapped address space will be accessed by the + process soon (and it is advantageous for the operating system to already + start paging in the data). + + @since UDK 3.2.12 + */ +#define osl_File_MapFlag_WillNeed ((sal_uInt32)(0x2)) + +/** Map a shared file into memory. + + Don't know what the "shared" is supposed to mean there? Also, + obviously this API can be used to map *part* of a file into + memory, and different parts can be mapped separately even. + + On Android, if the Handle refers to a file that is actually inside + the app package (.apk zip archive), no new mapping is created, + just a pointer to the file inside the already mapped .apk is + returned. + + @since UDK 3.2.10 + */ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_mapFile ( + oslFileHandle Handle, + void** ppAddr, + sal_uInt64 uLength, + sal_uInt64 uOffset, + sal_uInt32 uFlags +); + + +#ifndef ANDROID + +/** Unmap a shared file from memory. + + Ditto here, why do we need to mention "shared"? + + This function just won't work on Android in general where for + (uncompressed) files inside the .apk, per SDK conventions in the + /assets folder, osl_mapFile() returns a pointer to the file inside + the already by LibreOffice Android-specific bootstrapping code + mmapped .apk archive. We can't go and randomly munmap part of the + .apk archive. So this function is not present on Android. + + @since UDK 3.2.10 + */ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_unmapFile ( + void* pAddr, + sal_uInt64 uLength +); + +#endif + +/** Unmap a file segment from memory. + + Like osl_unmapFile(), but takes also the oslFileHandle argument + passed to osl_mapFile() when creating this mapping. + + On Android, for files below /assets, i.e. located inside the app + archive (.apk), this won't actually unmap anything; all the .apk + stays mapped. + + @since UDK 3.6 + */ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_unmapMappedFile ( + oslFileHandle Handle, + void* pAddr, + sal_uInt64 uLength +); + + +/** Read a number of bytes from a file. + + Reads a number of bytes from a file. The internal file pointer is + increased by the number of bytes read. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param pBuffer [out] + Points to a buffer which receives data. The buffer must be large enough + to hold uBytesRequested bytes. + + @param uBytesRequested [in] + Number of bytes which should be retrieved. + + @param pBytesRead [out] + On success the number of bytes which have actually been retrieved. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_ISDIR is a directory<br> + osl_File_E_BADF bad file<br> + osl_File_E_FAULT bad address<br> + osl_File_E_AGAIN operation would block<br> + osl_File_E_NOLINK link has been severed<br> + + @see osl_openFile() + @see osl_writeFile() + @see osl_readLine() + @see osl_setFilePos() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_readFile( + oslFileHandle Handle, void *pBuffer, sal_uInt64 uBytesRequested, sal_uInt64 *pBytesRead ); + + +/** Test if the end of a file is reached. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param pIsEOF [out] + Points to a variable that receives the end-of-file status. + + @return + osl_File_E_None on success <br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_ISDIR is a directory<br> + osl_File_E_BADF bad file<br> + osl_File_E_FAULT bad address<br> + osl_File_E_AGAIN operation would block<br> + osl_File_E_NOLINK link has been severed<p> + + @see osl_openFile() + @see osl_readFile() + @see osl_readLine() + @see osl_setFilePos() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_isEndOfFile( + oslFileHandle Handle, sal_Bool *pIsEOF ); + + +/** Write a number of bytes to a file. + + Writes a number of bytes to a file. + The internal file pointer is increased by the number of bytes read. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param pBuffer [in] + Points to a buffer which contains the data. + + @param uBytesToWrite [in] + Number of bytes which should be written. + + @param pBytesWritten [out] + On success the number of bytes which have actually been written. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_FBIG file too large<br> + osl_File_E_DQUOT quota exceeded<p> + osl_File_E_AGAIN operation would block<br> + osl_File_E_BADF bad file<br> + osl_File_E_FAULT bad address<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_IO on I/O errosr<br> + osl_File_E_NOLCK no record locks available<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_NOSPC no space left on device<br> + osl_File_E_NXIO no such device or address<br> + + @see osl_openFile() + @see osl_readFile() + @see osl_setFilePos() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_writeFile( + oslFileHandle Handle, const void *pBuffer, sal_uInt64 uBytesToWrite, sal_uInt64 *pBytesWritten ); + +/** Read a number of bytes from a specified offset in a file. + + The current position of the internal file pointer may or may not be changed. + + @since UDK 3.2.10 + */ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_readFileAt( + oslFileHandle Handle, + sal_uInt64 uOffset, + void* pBuffer, + sal_uInt64 uBytesRequested, + sal_uInt64* pBytesRead +); + + +/** Write a number of bytes to a specified offset in a file. + + The current position of the internal file pointer may or may not be changed. + + @since UDK 3.2.10 + */ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_writeFileAt( + oslFileHandle Handle, + sal_uInt64 uOffset, + const void* pBuffer, + sal_uInt64 uBytesToWrite, + sal_uInt64* pBytesWritten +); + + +/** Read a line from a file. + + Reads a line from a file. The new line delimiter is NOT returned! + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @param ppSequence [in/out] + A pointer pointer to a sal_Sequence that will hold the line read on success. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_ISDIR is a directory<br> + osl_File_E_BADF bad file<br> + osl_File_E_FAULT bad address<br> + osl_File_E_AGAIN operation would block<br> + osl_File_E_NOLINK link has been severed<p> + + @see osl_openFile() + @see osl_readFile() + @see osl_writeFile() + @see osl_setFilePos() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_readLine( + oslFileHandle Handle, sal_Sequence** ppSequence ); + +/** Synchronize the memory representation of a file with that on the physical medium. + + The function ensures that all modified data and attributes of the file associated with + the given file handle have been written to the physical medium. + In case the hard disk has a write cache enabled, the data may not really be on + permanent storage when osl_syncFile returns. + + @param Handle + [in] Handle to a file received by a previous call to osl_openFile(). + + @return + <dl> + <dt>osl_File_E_None</dt> + <dd>On success</dd> + <dt>osl_File_E_INVAL</dt> + <dd>The value of the input parameter is invalid</dd> + </dl> + <br><p><strong>In addition to these error codes others may occur as well, for instance:</strong></p><br> + <dl> + <dt>osl_File_E_BADF</dt> + <dd>The file associated with the given file handle is not open for writing</dd> + <dt>osl_File_E_IO</dt> + <dd>An I/O error occurred</dd> + <dt>osl_File_E_NOSPC</dt> + <dd>There is no enough space on the target device</dd> + <dt>osl_File_E_ROFS</dt> + <dd>The file associated with the given file handle is located on a read only file system</dd> + <dt>osl_File_E_TIMEDOUT</dt> + <dd>A remote connection timed out. This may happen when a file is on a remote location</dd> + </dl> + + @see osl_openFile() + @see osl_writeFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_syncFile( oslFileHandle Handle ); + +/** Close an open file. + + @param Handle [in] + Handle to a file received by a previous call to osl_openFile(). + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_BADF Bad file<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_NOSPC no space left on device<br> + osl_File_E_IO on I/O errors<br> + + @see osl_openFile() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_closeFile( oslFileHandle Handle ); + + +/** Create a directory. + + @param pustrDirectoryURL [in] + Full qualified URL of the directory to create. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_EXIST file exists<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_NOTDIR not a directory<br> + osl_File_E_ROFS read-only file system<br> + osl_File_E_NOSPC no space left on device<br> + osl_File_E_DQUOT quota exceeded<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_FAULT bad address<br> + osl_FileE_IO on I/O errors<br> + osl_File_E_MLINK too many links<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + + @see osl_removeDirectory() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createDirectory( rtl_uString* pustrDirectoryURL ); + + +/** Remove an empty directory. + + @param pustrDirectoryURL [in] + Full qualified URL of the directory. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_PERM operation not permitted<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_NOTDIR not a directory<br> + osl_File_E_NOTEMPTY directory not empty<br> + osl_File_E_FAULT bad address<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_BUSY device or resource busy<br> + osl_File_E_ROFS read-only file system<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_BUSY device or resource busy<br> + osl_File_E_EXIST file exists<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + + @see osl_createDirectory() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_removeDirectory( rtl_uString* pustrDirectoryURL ); + +/** Function pointer representing a function that will be called by osl_createDirectoryPath + if a directory has been created. + + To avoid unpredictable results the callee must not access the directory whose + creation is just notified. + + @param pData + [in] User specified data given in osl_createDirectoryPath. + + @param aDirectoryUrl + [in] The absolute file URL of the directory that was just created by + osl_createDirectoryPath. + + @see osl_createDirectoryPath +*/ +typedef void (SAL_CALL *oslDirectoryCreationCallbackFunc)(void* pData, rtl_uString* aDirectoryUrl); + +/** Create a directory path. + + The osl_createDirectoryPath function creates a specified directory path. + All nonexisting sub directories will be created. + <p><strong>PLEASE NOTE:</strong> You cannot rely on getting the error code + osl_File_E_EXIST for existing directories. Programming against this error + code is in general a strong indication of a wrong usage of osl_createDirectoryPath.</p> + + @param aDirectoryUrl + [in] The absolute file URL of the directory path to create. + A relative file URL will not be accepted. + + @param aDirectoryCreationCallbackFunc + [in] Pointer to a function that will be called synchronously + for each sub directory that was created. The value of this + parameter may be NULL, in this case notifications will not be + sent. + + @param pData + [in] User specified data to be passed to the directory creation + callback function. The value of this parameter may be arbitrary + and will not be interpreted by osl_createDirectoryPath. + + @return + <dl> + <dt>osl_File_E_None</dt> + <dd>On success</dd> + <dt>osl_File_E_INVAL</dt> + <dd>The format of the parameters was not valid</dd> + <dt>osl_File_E_ACCES</dt> + <dd>Permission denied</dd> + <dt>osl_File_E_EXIST</dt> + <dd>The final node of the specified directory path already exist</dd> + <dt>osl_File_E_NAMETOOLONG</dt> + <dd>The name of the specified directory path exceeds the maximum allowed length</dd> + <dt>osl_File_E_NOTDIR</dt> + <dd>A component of the specified directory path already exist as file in any part of the directory path</dd> + <dt>osl_File_E_ROFS</dt> + <dd>Read-only file system</dd> + <dt>osl_File_E_NOSPC</dt> + <dd>No space left on device</dd> + <dt>osl_File_E_DQUOT</dt> + <dd>Quota exceeded</dd> + <dt>osl_File_E_FAULT</dt> + <dd>Bad address</dd> + <dt>osl_File_E_IO</dt> + <dd>I/O error</dd> + <dt>osl_File_E_LOOP</dt> + <dd>Too many symbolic links encountered</dd> + <dt>osl_File_E_NOLINK</dt> + <dd>Link has been severed</dd> + <dt>osl_File_E_invalidError</dt> + <dd>An unknown error occurred</dd> + </dl> + + @see oslDirectoryCreationFunc + @see oslFileError + @see osl_createDirectory +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createDirectoryPath( + rtl_uString* aDirectoryUrl, + oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc, + void* pData); + +/** Remove a regular file. + + @param pustrFileURL [in] + Full qualified URL of the file to remove. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_ACCES permission denied<br> + osl_File_E_PERM operation not permitted<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_ISDIR is a directory<br> + osl_File_E_ROFS read-only file system<br> + osl_File_E_FAULT bad address<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_IO on I/O errors<br> + osl_File_E_BUSY device or resource busy<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + osl_File_E_TXTBSY text file busy<br> + + @see osl_openFile() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_removeFile( + rtl_uString* pustrFileURL ); + + +/** Copy a file to a new destination. + + Copies a file to a new destination. Copies only files not directories. + No assumptions should be made about preserving attributes or file time. + + @param pustrSourceFileURL [in] + Full qualified URL of the source file. + + @param pustrDestFileURL [in] + Full qualified URL of the destination file. A directory is NOT a valid destination file! + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_ACCES permission denied<br> + osl_File_E_PERM operation not permitted<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_ISDIR is a directory<br> + osl_File_E_ROFS read-only file system<p> + + @see osl_moveFile() + @see osl_removeFile() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_copyFile( + rtl_uString* pustrSourceFileURL, rtl_uString *pustrDestFileURL ); + + +/** Move a file or directory to a new destination or renames it. + + Moves a file or directory to a new destination or renames it. + File time and attributes are preserved. + + @param pustrSourceFileURL [in] + Full qualified URL of the source file. + + @param pustrDestFileURL [in] + Full qualified URL of the destination file. An existing directory is NOT a valid destination ! + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_ACCES permission denied<br> + osl_File_E_PERM operation not permitted<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_ROFS read-only file system<br> + + @see osl_copyFile() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_moveFile( + rtl_uString* pustrSourceFileURL, rtl_uString *pustrDestFileURL ); + + +/** Determine a valid unused canonical name for a requested name. + + Determines a valid unused canonical name for a requested name. + Depending on the Operating System and the File System the illegal characters are replaced by valid ones. + If a file or directory with the requested name already exists a new name is generated following + the common rules on the actual Operating System and File System. + + @param pustrRequestedURL [in] + Requested name of a file or directory. + + @param ppustrValidURL [out] + On success receives a name which is unused and valid on the actual Operating System and + File System. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + + @see osl_getFileStatus() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getCanonicalName( + rtl_uString *pustrRequestedURL, rtl_uString **ppustrValidURL); + + +/** Convert a path relative to a given directory into an full qualified file URL. + + Convert a path relative to a given directory into an full qualified file URL. + The function resolves symbolic links if possible and path ellipses, so on success + the resulting absolute path is fully resolved. + + @param pustrBaseDirectoryURL [in] + Base directory URL to which the relative path is related to. + + @param pustrRelativeFileURL [in] + An URL of a file or directory relative to the directory path specified by pustrBaseDirectoryURL + or an absolute path. + If pustrRelativeFileURL denotes an absolute path pustrBaseDirectoryURL will be ignored. + + @param ppustrAbsoluteFileURL [out] + On success it receives the full qualified absoulte file URL. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOMEM not enough memory for allocating structures <br> + osl_File_E_NOTDIR not a directory<br> + osl_File_E_ACCES permission denied<br> + osl_File_E_NOENT no such file or directory<br> + osl_File_E_NAMETOOLONG file name too long<br> + osl_File_E_OVERFLOW value too large for defined data type<br> + osl_File_E_FAULT bad address<br> + osl_File_E_INTR function call was interrupted<br> + osl_File_E_LOOP too many symbolic links encountered<br> + osl_File_E_MULTIHOP multihop attempted<br> + osl_File_E_NOLINK link has been severed<br> + + @see osl_getFileStatus() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getAbsoluteFileURL( + rtl_uString* pustrBaseDirectoryURL, + rtl_uString *pustrRelativeFileURL, + rtl_uString **ppustrAbsoluteFileURL ); + + +/** Convert a system dependend path into a file URL. + + @param pustrSystemPath [in] + A System dependent path of a file or directory. + + @param ppustrFileURL [out] + On success it receives the file URL. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + + @see osl_getSystemPathFromFileURL() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFileURLFromSystemPath( + rtl_uString *pustrSystemPath, rtl_uString **ppustrFileURL); + + +/** Searche a full qualified system path or a file URL. + + @param pustrFileName [in] + A system dependent path, a file URL, a file or relative directory. + + @param pustrSearchPath [in] + A list of system paths, in which a given file has to be searched. The Notation of a path list is + system dependend, e.g. on UNIX system "/usr/bin:/bin" and on Windows "C:\BIN;C:\BATCH". + These paths are only for the search of a file or a relative path, otherwise it will be ignored. + If pustrSearchPath is NULL or while using the search path the search failed, the function searches for + a matching file in all system directories and in the directories listed in the PATH environment + variable. + The value of an environment variable should be used (e.g. LD_LIBRARY_PATH) if the caller is not + aware of the Operating System and so doesn't know which path list delimiter to use. + + @param ppustrFileURL [out] + On success it receives the full qualified file URL. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOTDIR not a directory<br> + osl_File_E_NOENT no such file or directory not found<br> + + @see osl_getFileURLFromSystemPath() + @see osl_getSystemPathFromFileURL() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_searchFileURL( + rtl_uString *pustrFileName, rtl_uString *pustrSearchPath, rtl_uString **ppustrFileURL ); + + +/** Convert a file URL into a system dependend path. + + @param pustrFileURL [in] + A File URL. + + @param ppustrSystemPath [out] + On success it receives the system path. + + @return + osl_File_E_None on success + osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getFileURLFromSystemPath() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getSystemPathFromFileURL( + rtl_uString *pustrFileURL, rtl_uString **ppustrSystemPath); + + +/** Function pointer representing the function called back from osl_abbreviateSystemPath + + @param ustrText [in] + Text to calculate the width for + + @return + The width of the text specified by ustrText, e.g. it can return the width in pixel + or the width in character count. + + @see osl_abbreviateSystemPath() +*/ + +typedef sal_uInt32 (SAL_CALL *oslCalcTextWidthFunc)( rtl_uString *ustrText ); + + +/** Abbreviate a system notation path. + + @param ustrSystemPath [in] + The full system path to abbreviate + + @param pustrCompacted [out] + Receives the compacted system path on output + + @param pCalcWidth [in] + Function ptr that calculates the width of a string. Can be zero. + + @param uMaxWidth [in] + Maximum width allowed that is retunrned from pCalcWidth. + If pCalcWidth is zero the character count is assumed as width. + + @return + osl_File_E_None on success<br> + + @see oslCalcTextWidthFunc +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_abbreviateSystemPath( + rtl_uString *ustrSystemPath, + rtl_uString **pustrCompacted, + sal_uInt32 uMaxWidth, + oslCalcTextWidthFunc pCalcWidth ); + + +/** Set file attributes. + + @param pustrFileURL [in] + The full qualified file URL. + + @param uAttributes [in] + Attributes of the file to be set. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + + @see osl_getFileStatus() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFileAttributes( + rtl_uString *pustrFileURL, sal_uInt64 uAttributes ); + + +/** Set the file time. + + @param pustrFileURL [in] + The full qualified URL of the file. + + @param aCreationTime [in] + Creation time of the given file. + + @param aLastAccessTime [in] + Time of the last access of the given file. + + @param aLastWriteTime [in] + Time of the last modifying of the given file. + + @return + osl_File_E_None on success<br> + osl_File_E_INVAL the format of the parameters was not valid<br> + osl_File_E_NOENT no such file or directory not found<br> + + @see osl_getFileStatus() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFileTime( + rtl_uString *pustrFileURL, + const TimeValue *aCreationTime, + const TimeValue *aLastAccessTime, + const TimeValue *aLastWriteTime); + + +/** Retrieves the file URL of the system's temporary directory path + + @param[out] pustrTempDirURL + On success receives the URL of system's temporary directory path. + + @return + osl_File_E_None on success + osl_File_E_NOENT no such file or directory not found +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getTempDirURL( + rtl_uString **pustrTempDirURL ); + + +/** Creates a temporary file in the directory provided by the caller or the + directory returned by osl_getTempDirURL. + + Creates a temporary file in the directory provided by the caller or the + directory returned by osl_getTempDirURL. + Under UNIX Operating Systems the file will be created with read and write + access for the user exclusively. + If the caller requests only a handle to the open file but not the name of + it, the file will be automatically removed on close else the caller is + responsible for removing the file on success. + + Description of the different pHandle, ppustrTempFileURL parameter combinations. + pHandle is 0 and ppustrTempDirURL is 0 - this combination is invalid + pHandle is not 0 and ppustrTempDirURL is 0 - a handle to the open file + will be returned on success and the file will be automatically removed on close. + pHandle is 0 and ppustrTempDirURL is not 0 - the name of the file will be returned, + the caller is responsible for opening, closing and removing the file. + pHandle is not 0 and ppustrTempDirURL is not 0 - a handle to the open file as well as + the file name will be returned, the caller is responsible for closing and removing + the file. + + @param pustrDirectoryURL [in] + Specifies the full qualified URL where the temporary file should be created. + If pustrDirectoryURL is 0 the path returned by osl_getTempDirURL will be used. + + @param pHandle [out] + On success receives a handle to the open file. If pHandle is 0 the file will + be closed on return, in this case ppustrTempFileURL must not be 0. + + @param ppustrTempFileURL [out] + On success receives the full qualified URL of the temporary file. + If ppustrTempFileURL is 0 the file will be automatically removed on close, + in this case pHandle must not be 0. + If ppustrTempFileURL is not 0 the caller receives the name of the created + file and is responsible for removing the file, in this case + *ppustrTempFileURL must be 0 or must point to a valid rtl_uString. + + @return + osl_File_E_None on success + osl_File_E_INVAL the format of the parameter is invalid + osl_File_E_NOMEM not enough memory for allocating structures + osl_File_E_ACCES Permission denied + osl_File_E_NOENT No such file or directory + osl_File_E_NOTDIR Not a directory + osl_File_E_ROFS Read-only file system + osl_File_E_NOSPC No space left on device + osl_File_E_DQUOT Quota exceeded + + @see osl_getTempDirURL() +*/ + +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createTempFile( + rtl_uString* pustrDirectoryURL, + oslFileHandle* pHandle, + rtl_uString** ppustrTempFileURL); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_FILE_H_ */ + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/file.hxx b/include/osl/file.hxx new file mode 100644 index 000000000000..ee52cd570840 --- /dev/null +++ b/include/osl/file.hxx @@ -0,0 +1,1979 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_FILE_HXX_ +#define _OSL_FILE_HXX_ + +#include "sal/config.h" + +#include <string.h> + +#include <cassert> + +#include <osl/time.h> +#include <rtl/ustring.hxx> + +#include <osl/file.h> +#include <rtl/byteseq.hxx> + +#include <stdio.h> + +namespace osl +{ + + +// ----------------------------------------------------------------------------- +/** Base class for all File System specific objects. + + @see Directory + @see DirectoryItem + @see File + */ + +class FileBase +{ +public: + + enum RC { + E_None = osl_File_E_None, + E_PERM = osl_File_E_PERM, + E_NOENT = osl_File_E_NOENT, + E_SRCH = osl_File_E_SRCH, + E_INTR = osl_File_E_INTR, + E_IO = osl_File_E_IO, + E_NXIO = osl_File_E_NXIO, + E_2BIG = osl_File_E_2BIG, + E_NOEXEC = osl_File_E_NOEXEC, + E_BADF = osl_File_E_BADF, + E_CHILD = osl_File_E_CHILD, + E_AGAIN = osl_File_E_AGAIN, + E_NOMEM = osl_File_E_NOMEM, + E_ACCES = osl_File_E_ACCES, + E_FAULT = osl_File_E_FAULT, + E_BUSY = osl_File_E_BUSY, + E_EXIST = osl_File_E_EXIST, + E_XDEV = osl_File_E_XDEV, + E_NODEV = osl_File_E_NODEV, + E_NOTDIR = osl_File_E_NOTDIR, + E_ISDIR = osl_File_E_ISDIR, + E_INVAL = osl_File_E_INVAL, + E_NFILE = osl_File_E_NFILE, + E_MFILE = osl_File_E_MFILE, + E_NOTTY = osl_File_E_NOTTY, + E_FBIG = osl_File_E_FBIG, + E_NOSPC = osl_File_E_NOSPC, + E_SPIPE = osl_File_E_SPIPE, + E_ROFS = osl_File_E_ROFS, + E_MLINK = osl_File_E_MLINK, + E_PIPE = osl_File_E_PIPE, + E_DOM = osl_File_E_DOM, + E_RANGE = osl_File_E_RANGE, + E_DEADLK = osl_File_E_DEADLK, + E_NAMETOOLONG = osl_File_E_NAMETOOLONG, + E_NOLCK = osl_File_E_NOLCK, + E_NOSYS = osl_File_E_NOSYS, + E_NOTEMPTY = osl_File_E_NOTEMPTY, + E_LOOP = osl_File_E_LOOP, + E_ILSEQ = osl_File_E_ILSEQ, + E_NOLINK = osl_File_E_NOLINK, + E_MULTIHOP = osl_File_E_MULTIHOP, + E_USERS = osl_File_E_USERS, + E_OVERFLOW = osl_File_E_OVERFLOW, + E_NOTREADY = osl_File_E_NOTREADY, + E_invalidError = osl_File_E_invalidError, /* unmapped error: always last entry in enum! */ + E_TIMEDOUT = osl_File_E_TIMEDOUT, + E_NETWORK = osl_File_E_NETWORK + }; + + +public: + + /** Determine a valid unused canonical name for a requested name. + + Determines a valid unused canonical name for a requested name. + Depending on the Operating System and the File System the illegal characters are replaced by valid ones. + If a file or directory with the requested name already exists a new name is generated following + the common rules on the actual Operating System and File System. + + @param ustrRequestedURL [in] + Requested name of a file or directory. + + @param ustrValidURL [out] + On success receives a name which is unused and valid on the actual Operating System and + File System. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + + @see DirectoryItem::getFileStatus() + */ + + static inline RC getCanonicalName( const ::rtl::OUString& ustrRequestedURL, ::rtl::OUString& ustrValidURL ) + { + return (RC) osl_getCanonicalName( ustrRequestedURL.pData, &ustrValidURL.pData ); + } + + /** Convert a path relative to a given directory into an full qualified file URL. + + Convert a path relative to a given directory into an full qualified file URL. + The function resolves symbolic links if possible and path ellipses, so on success + the resulting absolute path is fully resolved. + + @param ustrBaseDirectoryURL [in] + Base directory URL to which the relative path is related to. + + @param ustrRelativeFileURL [in] + An URL of a file or directory relative to the directory path specified by ustrBaseDirectoryURL + or an absolute path. + If ustrRelativeFileURL denotes an absolute path ustrBaseDirectoryURL will be ignored. + + @param ustrAbsoluteFileURL [out] + On success it receives the full qualified absoulte file URL. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_NOTDIR not a directory + E_ACCES permission denied + E_NOENT no such file or directory + E_NAMETOOLONG file name too long + E_OVERFLOW value too large for defined data type + E_FAULT bad address + E_INTR function call was interrupted + E_LOOP too many symbolic links encountered + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + + @see DirectoryItem::getFileStatus() + */ + + static inline RC getAbsoluteFileURL( const ::rtl::OUString& ustrBaseDirectoryURL, const ::rtl::OUString& ustrRelativeFileURL, ::rtl::OUString& ustrAbsoluteFileURL ) + { + return (RC) osl_getAbsoluteFileURL( ustrBaseDirectoryURL.pData, ustrRelativeFileURL.pData, &ustrAbsoluteFileURL.pData ); + } + + /** Convert a file URL into a system dependend path. + + @param ustrFileURL [in] + A File URL. + + @param ustrSystemPath [out] + On success it receives the system path. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + + @see getFileURLFromSystemPath() + */ + + static inline RC getSystemPathFromFileURL( const ::rtl::OUString& ustrFileURL, ::rtl::OUString& ustrSystemPath ) + { + return (RC) osl_getSystemPathFromFileURL( ustrFileURL.pData, &ustrSystemPath.pData ); + } + + /** Convert a system dependend path into a file URL. + + @param ustrSystemPath [in] + A System dependent path of a file or directory. + + @param ustrFileURL [out] + On success it receives the file URL. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + + @see getSystemPathFromFileURL() + */ + + static inline RC getFileURLFromSystemPath( const ::rtl::OUString& ustrSystemPath, ::rtl::OUString& ustrFileURL ) + { + return (RC) osl_getFileURLFromSystemPath( ustrSystemPath.pData, &ustrFileURL.pData ); + } + + /** Searche a full qualified system path or a file URL. + + @param ustrFileName [in] + A system dependent path, a file URL, a file or relative directory + + @param ustrSearchPath [in] + A list of system paths, in which a given file has to be searched. The Notation of a path list is + system dependend, e.g. on UNIX system "/usr/bin:/bin" and on Windows "C:\BIN;C:\BATCH". + These paths are only for the search of a file or a relative path, otherwise it will be ignored. + If ustrSearchPath is NULL or while using the search path the search failed, the function searches for + a matching file in all system directories and in the directories listed in the PATH environment + variable. + The value of an environment variable should be used (e.g. LD_LIBRARY_PATH) if the caller is not + aware of the Operating System and so doesn't know which path list delimiter to use. + + @param ustrFileURL [out] + On success it receives the full qualified file URL. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOTDIR not a directory + E_NOENT no such file or directory not found + + @see getFileURLFromSystemPath() + @see getSystemPathFromFileURL() + */ + + static inline RC searchFileURL( const ::rtl::OUString& ustrFileName, const ::rtl::OUString& ustrSearchPath, ::rtl::OUString& ustrFileURL ) + { + return (RC) osl_searchFileURL( ustrFileName.pData, ustrSearchPath.pData, &ustrFileURL.pData ); + } + + /** Retrieves the file URL of the system's temporary directory path. + + @param[out] ustrTempDirURL + On success receives the URL of system's temporary directory path. + + @return + E_None on success + E_NOENT no such file or directory not found + */ + + static inline RC getTempDirURL( ::rtl::OUString& ustrTempDirURL ) + { + return (RC) osl_getTempDirURL( &ustrTempDirURL.pData ); + } + + /** Creates a temporary file in the directory provided by the caller or the + directory returned by getTempDirURL. + Under UNIX Operating Systems the file will be created with read and write + access for the user exclusively. + If the caller requests only a handle to the open file but not the name of + it, the file will be automatically removed on close else the caller is + responsible for removing the file on success.<br><br> + + @param pustrDirectoryURL [in] + Specifies the full qualified URL where the temporary file should be created. + If pustrDirectoryURL is 0 the path returned by osl_getTempDirURL will be used. + + @param pHandle [out] + On success receives a handle to the open file. + If pHandle is 0 the file will be closed on return, in this case + pustrTempFileURL must not be 0. + + @param pustrTempFileURL [out] + On success receives the full qualified URL of the temporary file. + If pustrTempFileURL is 0 the file will be automatically removed + on close, in this case pHandle must not be 0. + If pustrTempFileURL is not 0 the caller receives the name of the + created file and is responsible for removing the file. + + Description of the different pHandle, ppustrTempFileURL parameter combinations. + pHandle is 0 and pustrTempDirURL is 0 - this combination is invalid<br> + pHandle is not 0 and pustrTempDirURL is 0 - a handle to the open file + will be returned on success and the file will be automatically removed on close<br> + pHandle is 0 and pustrTempDirURL is not 0 - the name of the file will be + returned, the caller is responsible for opening, closing and removing the file.<br> + pHandle is not 0 and pustrTempDirURL is not 0 - a handle to the open file as well as + the file name will be returned, the caller is responsible for closing and removing + the file.<br> + + @return + E_None on success + E_INVAL the format of the parameter is invalid + E_NOMEM not enough memory for allocating structures + E_ACCES Permission denied + E_NOENT No such file or directory + E_NOTDIR Not a directory + E_ROFS Read-only file system + E_NOSPC No space left on device + E_DQUOT Quota exceeded + + @see getTempDirURL() + */ + + static inline RC createTempFile( + ::rtl::OUString* pustrDirectoryURL, + oslFileHandle* pHandle, + ::rtl::OUString* pustrTempFileURL) + { + rtl_uString* pustr_dir_url = pustrDirectoryURL ? pustrDirectoryURL->pData : 0; + rtl_uString** ppustr_tmp_file_url = pustrTempFileURL ? &pustrTempFileURL->pData : 0; + + return (RC) osl_createTempFile(pustr_dir_url, pHandle, ppustr_tmp_file_url); + } +}; + + +// ----------------------------------------------------------------------------- +/** The VolumeDevice class. + + @see VolumeInfo +*/ + +class VolumeDevice : public FileBase +{ + oslVolumeDeviceHandle _aHandle; + +public: + + /** Constructor. + */ + + VolumeDevice() : _aHandle( NULL ) + { + } + + /** Copy constructor. + + @param rDevice + The other volume device. + */ + + VolumeDevice( const VolumeDevice & rDevice ) + { + _aHandle = rDevice._aHandle; + if ( _aHandle ) + osl_acquireVolumeDeviceHandle( _aHandle ); + } + + /** Destructor. + */ + + ~VolumeDevice() + { + if ( _aHandle ) + osl_releaseVolumeDeviceHandle( _aHandle ); + } + + /** Assignment operator. + + @param rDevice + The other volume device. + */ + + inline VolumeDevice & operator =( const VolumeDevice & rDevice ) + { + oslVolumeDeviceHandle newHandle = rDevice._aHandle; + + if ( newHandle ) + osl_acquireVolumeDeviceHandle( newHandle ); + + if ( _aHandle ) + osl_releaseVolumeDeviceHandle( _aHandle ); + + _aHandle = newHandle; + + return *this; + } + + /** Get the full qualified URL where a device is mounted to. + + @return + The full qualified URL where the device is mounted to. + */ + inline rtl::OUString getMountPath() + { + rtl::OUString aPath; + osl_getVolumeDeviceMountPath( _aHandle, &aPath.pData ); + return aPath; + } + + friend class VolumeInfo; +}; + +// ----------------------------------------------------------------------------- + +class Directory; + +/** The VolumeInfo class. + + Neither copy nor assignment is allowed for this class. + + @see Directory::getVolumeInfo +*/ + + +class VolumeInfo +{ + oslVolumeInfo _aInfo; + sal_uInt32 _nMask; + VolumeDevice _aDevice; + + /** Copy constructor. + */ + + VolumeInfo( VolumeInfo& ); + + /** Assginment operator. + */ + + VolumeInfo& operator = ( VolumeInfo& ); + +public: + + /** Constructor. + + @param nMask + Set of flags decribing the demanded information. + */ + + VolumeInfo( sal_uInt32 nMask ): _nMask( nMask ) + { + _aInfo.uStructSize = sizeof( oslVolumeInfo ); + memset( &_aInfo.uValidFields, 0, sizeof( oslVolumeInfo ) - sizeof( sal_uInt32 ) ); + _aInfo.pDeviceHandle = &_aDevice._aHandle; + } + + /** Destructor. + */ + + ~VolumeInfo() + { + if( _aInfo.ustrFileSystemName ) + rtl_uString_release( _aInfo.ustrFileSystemName ); + } + + /** Check if specified fields are valid. + + @param nMask + Set of flags for the fields to check. + + @return sal_True if all fields are valid else sal_False. + */ + + inline sal_Bool isValid( sal_uInt32 nMask ) const + { + return ( nMask & _aInfo.uValidFields ) == nMask; + } + + /** Check the remote flag. + + @return + sal_True if Attributes are valid and the volume is remote else sal_False. + */ + + inline sal_Bool getRemoteFlag() const + { + return 0 != (_aInfo.uAttributes & osl_Volume_Attribute_Remote); + } + + /** Check the removeable flag. + + @return + sal_True if attributes are valid and the volume is removable else sal_False. + */ + + inline sal_Bool getRemoveableFlag() const + { + return 0 != (_aInfo.uAttributes & osl_Volume_Attribute_Removeable); + } + + /** Check the compact disc flag. + + @return + sal_True if attributes are valid and the volume is a CDROM else sal_False. + */ + + inline sal_Bool getCompactDiscFlag() const + { + return 0 != (_aInfo.uAttributes & osl_Volume_Attribute_CompactDisc); + } + + /** Check the floppy disc flag. + + @return + sal_True if attributes are valid and the volume is a floppy disk else sal_False. + */ + + inline sal_Bool getFloppyDiskFlag() const + { + return 0 != (_aInfo.uAttributes & osl_Volume_Attribute_FloppyDisk); + } + + /** Check the fixed disk flag. + + @return + sal_True if attributes are valid and the volume is a fixed disk else sal_False. + */ + + inline sal_Bool getFixedDiskFlag() const + { + return 0 != (_aInfo.uAttributes & osl_Volume_Attribute_FixedDisk); + } + + /** Check the RAM disk flag. + + @return + sal_True if attributes are valid and the volume is a RAM disk else sal_False. + */ + + inline sal_Bool getRAMDiskFlag() const + { + return 0 != (_aInfo.uAttributes & osl_Volume_Attribute_RAMDisk); + } + + /** Determine the total space of a volume device. + + @return + The total diskspace of this volume if this information is valid, + 0 otherwise. + */ + + inline sal_uInt64 getTotalSpace() const + { + return _aInfo.uTotalSpace; + } + + /** Determine the free space of a volume device. + + @return + The free diskspace of this volume if this information is valid, + 0 otherwise. + */ + + inline sal_uInt64 getFreeSpace() const + { + return _aInfo.uFreeSpace; + } + + /** Determine the used space of a volume device. + + @return + The used diskspace of this volume if this information is valid, + 0 otherwise. + */ + + inline sal_uInt64 getUsedSpace() const + { + return _aInfo.uUsedSpace; + } + + /** Determine the maximal length of a file name. + + @return + The maximal length of a file name if this information is valid, + 0 otherwise. + */ + + inline sal_uInt32 getMaxNameLength() const + { + return _aInfo.uMaxNameLength; + } + + /** Determine the maximal length of a path name. + + @return + The maximal length of a path if this information is valid, + 0 otherwise. + */ + + inline sal_uInt32 getMaxPathLength() const + { + return _aInfo.uMaxPathLength; + } + + /** Determine the name of the volume device's File System. + + @return + The name of the volume's fielsystem if this information is valid, + otherwise an empty string. + */ + + inline ::rtl::OUString getFileSystemName() const + { + return _aInfo.ustrFileSystemName ? ::rtl::OUString( _aInfo.ustrFileSystemName ) : ::rtl::OUString(); + } + + + /** Get the volume device handle. + + @return + The device handle of the volume if this information is valid, + otherwise returns NULL; + */ + + inline VolumeDevice getDeviceHandle() const + { + return _aDevice; + } + + /** Return whether the file system is case sensitive or + case insensitive + + @return + true if the file system is case sensitive false otherwise + */ + bool isCaseSensitiveFileSystem() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_Case_Sensitive); + } + + /** Return whether the file system preserves the case of + file and directory names or not + + @return + true if the file system preserves the case of file and + directory names false otherwise + */ + bool isCasePreservingFileSystem() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_Case_Is_Preserved); + } + + friend class Directory; +}; + +// ----------------------------------------------------------------------------- +class DirectoryItem; + +/** The FileStatus class. + + @see DirectoryItem::getFileStatus +*/ + +class FileStatus +{ + oslFileStatus _aStatus; + sal_uInt32 _nMask; + + /** Copy constructor. + */ + + FileStatus( FileStatus& ); + + /** Assignment operator. + */ + + FileStatus& operator = ( FileStatus& ); + +public: + + enum Type { + Directory = osl_File_Type_Directory, + Volume = osl_File_Type_Volume, + Regular = osl_File_Type_Regular, + Fifo = osl_File_Type_Fifo, + Socket = osl_File_Type_Socket, + Link = osl_File_Type_Link, + Special = osl_File_Type_Special, + Unknown = osl_File_Type_Unknown + }; + + /** Constructor. + + @param nMask + Set of flags decribing the demanded information. + */ + + FileStatus( sal_uInt32 nMask ): _nMask( nMask ) + { + _aStatus.uStructSize = sizeof( oslFileStatus ); + memset( &_aStatus.uValidFields, 0, sizeof( oslFileStatus ) - sizeof( sal_uInt32 ) ); + } + + /** Destructor. + */ + + ~FileStatus() + { + if ( _aStatus.ustrFileURL ) + rtl_uString_release( _aStatus.ustrFileURL ); + if ( _aStatus.ustrLinkTargetURL ) + rtl_uString_release( _aStatus.ustrLinkTargetURL ); + if ( _aStatus.ustrFileName ) + rtl_uString_release( _aStatus.ustrFileName ); + } + + /** Check if specified fields are valid. + + @param nMask + Set of flags for the fields to check. + + @return + sal_True if all fields are valid else sal_False. + */ + + inline sal_Bool isValid( sal_uInt32 nMask ) const + { + return ( nMask & _aStatus.uValidFields ) == nMask; + } + + /** Get the file type. + + @return + The file type. + */ + inline Type getFileType() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_Type), "sal.osl", + "no FileStatus Type determined"); + return isValid(osl_FileStatus_Mask_Type) + ? static_cast< Type >(_aStatus.eType) : Unknown; + } + + /** Is it a directory? + This method returns True for both directories, and volumes. + + @return + True if it's a directory, False otherwise. + + @see getFileType + @since LibreOffice 3.6 + */ + inline sal_Bool isDirectory() const + { + return ( getFileType() == Directory || getFileType() == Volume ); + } + + /** Is it a regular file? + + @return + True if it's a regular file, False otherwise. + + @see getFileType + @see isFile + @see isLink + @since LibreOffice 3.6 + */ + inline sal_Bool isRegular() const + { + return ( getFileType() == Regular ); + } + + /** Is it a link? + + @return + True if it's a link, False otherwise. + + @see getFileType + @since LibreOffice 3.6 + */ + inline sal_Bool isLink() const + { + return ( getFileType() == Link ); + } + + /** Get the file attributes. + + @return + The set of attribute flags of this file. + */ + + inline sal_uInt64 getAttributes() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_Attributes), "sal.osl", + "no FileStatus Attributes determined"); + return _aStatus.uAttributes; + } + + /** Get the creation time of this file. + + @return + The creation time if this information is valid, an uninitialized + TimeValue otherwise. + */ + + inline TimeValue getCreationTime() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_CreationTime), "sal.osl", + "no FileStatus CreationTime determined"); + return _aStatus.aCreationTime; + } + + /** Get the file access time. + + @return + The last access time if this information is valid, an uninitialized + TimeValue otherwise. + */ + + inline TimeValue getAccessTime() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_AccessTime), "sal.osl", + "no FileStatus AccessTime determined"); + return _aStatus.aAccessTime; + } + + /** Get the file modification time. + + @return + The last modified time if this information is valid, an uninitialized + TimeValue otherwise. + */ + + inline TimeValue getModifyTime() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_ModifyTime), "sal.osl", + "no FileStatus ModifyTime determined"); + return _aStatus.aModifyTime; + } + + /** Get the size of the file. + + @return + The actual file size if this information is valid, 0 otherwise. + */ + + inline sal_uInt64 getFileSize() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_FileSize), "sal.osl", + "no FileStatus FileSize determined"); + return _aStatus.uFileSize; + } + + /** Get the file name. + + @return + The file name if this information is valid, an empty string otherwise. + */ + + inline ::rtl::OUString getFileName() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_FileName), "sal.osl", + "no FileStatus FileName determined"); + return isValid(osl_FileStatus_Mask_FileName) + ? rtl::OUString(_aStatus.ustrFileName) : rtl::OUString(); + } + + + /** Get the URL of the file. + + @return + The full qualified URL of the file if this information is valid, an + empty string otherwise. + */ + + inline ::rtl::OUString getFileURL() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_FileURL), "sal.osl", + "no FileStatus FileURL determined"); + return isValid(osl_FileStatus_Mask_FileURL) + ? rtl::OUString(_aStatus.ustrFileURL) : rtl::OUString(); + } + + /** Get the link target URL. + + @return + The link target URL if this information is valid, an empty string + otherwise. + */ + + inline ::rtl::OUString getLinkTargetURL() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_LinkTargetURL), "sal.osl", + "no FileStatus LinkTargetURL determined"); + return isValid(osl_FileStatus_Mask_LinkTargetURL) + ? rtl::OUString(_aStatus.ustrLinkTargetURL) : rtl::OUString(); + } + + friend class DirectoryItem; +}; + + +// ----------------------------------------------------------------------------- +/** The file class object provides access to file contents and attributes. + + @see Directory + @see DirectoryItem + */ + +class File: public FileBase +{ + oslFileHandle _pData; + ::rtl::OUString _aPath; + + /** Copy constructor. + */ + + File( File& ); + + /** Assginment operator. + */ + + File& operator = ( File& ); + +public: + + /** Constructor. + + @param ustrFileURL [in] + The full qualified URL of the file. Relative paths are not allowed. + */ + + File( const ::rtl::OUString& ustrFileURL ): _pData( 0 ), _aPath( ustrFileURL ) {} + + /** Destructor + */ + + inline ~File() + { + close(); + } + + /** Obtain the URL. + + @return + the URL with which this File instance was created. + + @since LibreOffice 4.1 + */ + inline rtl::OUString getURL() const { return _aPath; } + + /** Open a regular file. + + Open a file. Only regular files can be openend. + + @param uFlags [in] + Specifies the open mode. + + @return + E_None on success + E_NOMEM not enough memory for allocating structures + E_INVAL the format of the parameters was not valid + E_NAMETOOLONG pathname was too long + E_NOENT no such file or directory + E_ACCES permission denied + E_AGAIN a write lock could not be established + E_NOTDIR not a directory + E_NXIO no such device or address + E_NODEV no such device + E_ROFS read-only file system + E_TXTBSY text file busy + E_FAULT bad address + E_LOOP too many symbolic links encountered + E_NOSPC no space left on device + E_ISDIR is a directory + E_MFILE too many open files used by the process + E_NFILE too many open files in the system + E_DQUOT quota exceeded + E_EXIST file exists + E_INTR function call was interrupted + E_IO on I/O errors + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + E_EOVERFLOW value too large for defined data type + + @see close() + @see setPos() + @see getPos() + @see read() + @see write() + @see getSize() + @see setSize() + */ + + inline RC open( sal_uInt32 uFlags ) + { + return (RC) osl_openFile( _aPath.pData, &_pData, uFlags ); + } + + /** Close an open file. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_BADF Bad file + E_INTR function call was interrupted + E_NOLINK link has been severed + E_NOSPC no space left on device + E_IO on I/O errors + + @see open() + */ + + inline RC close() + { + oslFileError Error = osl_File_E_BADF; + + if( _pData ) + { + Error=osl_closeFile( _pData ); + _pData = NULL; + } + + return (RC) Error; + } + + /** Set the internal position pointer of an open file. + + @param uHow [in] + Distance to move the internal position pointer (from uPos). + + @param uPos [in] + Absolute position from the beginning of the file. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see getPos() + */ + + inline RC setPos( sal_uInt32 uHow, sal_Int64 uPos ) SAL_WARN_UNUSED_RESULT + { + return (RC) osl_setFilePos( _pData, uHow, uPos ); + } + + /** Retrieve the current position of the internal pointer of an open file. + + @param uPos [out] + On success receives the current position of the file pointer. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see setPos() + @see read() + @see write() + */ + + inline RC getPos( sal_uInt64& uPos ) + { + return (RC) osl_getFilePos( _pData, &uPos ); + } + + /** Test if the end of a file is reached. + + @param pIsEOF [out] + Points to a variable that receives the end-of-file status. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_INTR function call was interrupted + E_IO on I/O errors + E_ISDIR is a directory + E_BADF bad file + E_FAULT bad address + E_AGAIN operation would block + E_NOLINK link has been severed + + @see open() + @see read() + @see readLine() + @see setPos() + */ + + inline RC isEndOfFile( sal_Bool *pIsEOF ) + { + return (RC) osl_isEndOfFile( _pData, pIsEOF ); + } + + /** Set the file size of an open file. + + Sets the file size of an open file. The file can be truncated or enlarged by the function. + The position of the file pointer is not affeced by this function. + + @param uSize [in] + New size in bytes. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see setPos() + @see getStatus() + */ + + inline RC setSize( sal_uInt64 uSize ) + { + return (RC) osl_setFileSize( _pData, uSize ); + } + + /** Get the file size of an open file. + + Gets the file size of an open file. + The position of the file pointer is not affeced by this function. + + @param rSize [out] + Current size in bytes. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see setPos() + @see getSize() + @see setSize() + @see getStatus() + */ + + inline RC getSize( sal_uInt64 &rSize ) + { + return (RC) osl_getFileSize( _pData, &rSize ); + } + + /** Read a number of bytes from a file. + + Reads a number of bytes from a file. The internal file pointer is + increased by the number of bytes read. + + @param pBuffer [out] + Points to a buffer which receives data. The buffer must be large enough + to hold uBytesRequested bytes. + + @param uBytesRequested [in] + Number of bytes which should be retrieved. + + @param rBytesRead [out] + On success the number of bytes which have actually been retrieved. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_INTR function call was interrupted + E_IO on I/O errors + E_ISDIR is a directory + E_BADF bad file + E_FAULT bad address + E_AGAIN operation would block + E_NOLINK link has been severed + + @see open() + @see write() + @see readLine() + @see setPos() + */ + + inline RC read( void *pBuffer, sal_uInt64 uBytesRequested, sal_uInt64& rBytesRead ) + { + return (RC) osl_readFile( _pData, pBuffer, uBytesRequested, &rBytesRead ); + } + + /** Write a number of bytes to a file. + + Writes a number of bytes to a file. + The internal file pointer is increased by the number of bytes read. + + @param pBuffer [in] + Points to a buffer which contains the data. + + @param uBytesToWrite [in] + Number of bytes which should be written. + + @param rBytesWritten [out] + On success the number of bytes which have actually been written. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_FBIG file too large + E_DQUOT quota exceeded + E_AGAIN operation would block + E_BADF bad file + E_FAULT bad address + E_INTR function call was interrupted + E_IO on I/O errosr + E_NOLCK no record locks available + E_NOLINK link has been severed + E_NOSPC no space left on device + E_NXIO no such device or address + + @see open() + @see read() + @see setPos() + */ + + inline RC write(const void *pBuffer, sal_uInt64 uBytesToWrite, sal_uInt64& rBytesWritten) + { + return (RC) osl_writeFile( _pData, pBuffer, uBytesToWrite, &rBytesWritten ); + } + + + /** Read a line from a file. + + Reads a line from a file. The new line delimiter is NOT returned! + + @param aSeq [in/out] + A reference to a ::rtl::ByteSequence that will hold the line read on success. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_INTR function call was interrupted + E_IO on I/O errors + E_ISDIR is a directory + E_BADF bad file + E_FAULT bad address + E_AGAIN operation would block + E_NOLINK link has been severed + + @see open() + @see read() + @see write() + @see setPos() + */ + + inline RC readLine( ::rtl::ByteSequence& aSeq ) + { + return (RC) osl_readLine( _pData, reinterpret_cast<sal_Sequence**>(&aSeq) ); + } + + /** Synchronize the memory representation of a file with that on the physical medium. + + The function ensures that all modified data and attributes of the file associated with + the given file handle have been written to the physical medium. + In case the hard disk has a write cache enabled, the data may not really be on + permanent storage when osl_syncFile returns. + + @return + <dl> + <dt>E_None</dt> + <dd>On success</dd> + <dt>E_INVAL</dt> + <dd>The value of the input parameter is invalid</dd> + <br><p><strong>In addition to these error codes others may occur as well, for instance:</strong></p><br> + <dt>E_BADF</dt> + <dd>The file is not open for writing</dd> + <dt>E_IO</dt> + <dd>An I/O error occurred</dd> + <dt>E_NOSPC</dt> + <dd>There is no enough space on the target device</dd> + <dt>E_ROFS</dt> + <dd>The file is located on a read only file system</dd> + <dt>E_TIMEDOUT</dt> + <dd>A remote connection timed out. This may happen when a file is on a remote location</dd> + </dl> + + @see osl_syncFile() + @see open() + @see write() + */ + inline RC sync() const + { + OSL_PRECOND(_pData, "File::sync(): File not open"); + return (RC)osl_syncFile(_pData); + } + + /** Copy a file to a new destination. + + Copies a file to a new destination. Copies only files not directories. + No assumptions should be made about preserving attributes or file time. + + @param ustrSourceFileURL [in] + Full qualified URL of the source file. + + @param ustrDestFileURL [in] + Full qualified URL of the destination file. A directory is NOT a valid destination file! + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_ACCES permission denied + E_PERM operation not permitted + E_NAMETOOLONG file name too long + E_NOENT no such file or directory + E_ISDIR is a directory + E_ROFS read-only file system + + @see move() + @see remove() + */ + + inline static RC copy( const ::rtl::OUString& ustrSourceFileURL, const ::rtl::OUString& ustrDestFileURL ) + { + return (RC) osl_copyFile( ustrSourceFileURL.pData, ustrDestFileURL.pData ); + } + + /** Move a file or directory to a new destination or renames it. + + Moves a file or directory to a new destination or renames it. + File time and attributes are preserved. + + @param ustrSourceFileURL [in] + Full qualified URL of the source file. + + @param ustrDestFileURL [in] + Full qualified URL of the destination file. An existing directory is NOT a valid destination ! + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_ACCES permission denied + E_PERM operation not permitted + E_NAMETOOLONG file name too long + E_NOENT no such file or directory + E_ROFS read-only file system + + @see copy() + */ + + inline static RC move( const ::rtl::OUString& ustrSourceFileURL, const ::rtl::OUString& ustrDestFileURL ) + { + return (RC) osl_moveFile( ustrSourceFileURL.pData, ustrDestFileURL.pData ); + } + + /** Remove a regular file. + + @param ustrFileURL [in] + Full qualified URL of the file to remove. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_ACCES permission denied + E_PERM operation not permitted + E_NAMETOOLONG file name too long + E_NOENT no such file or directory + E_ISDIR is a directory + E_ROFS read-only file system + E_FAULT bad address + E_LOOP too many symbolic links encountered + E_IO on I/O errors + E_BUSY device or resource busy + E_INTR function call was interrupted + E_LOOP too many symbolic links encountered + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + E_TXTBSY text file busy + + @see open() + */ + + inline static RC remove( const ::rtl::OUString& ustrFileURL ) + { + return (RC) osl_removeFile( ustrFileURL.pData ); + } + + /** Set file attributes. + + @param ustrFileURL [in] + The full qualified file URL. + + @param uAttributes [in] + Attributes of the file to be set. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + + @see FileStatus + */ + + inline static RC setAttributes( const ::rtl::OUString& ustrFileURL, sal_uInt64 uAttributes ) + { + return (RC) osl_setFileAttributes( ustrFileURL.pData, uAttributes ); + } + + /** Set the file time. + + @param ustrFileURL [in] + The full qualified URL of the file. + + @param rCreationTime [in] + Creation time of the given file. + + @param rLastAccessTime [in] + Time of the last access of the given file. + + @param rLastWriteTime [in] + Time of the last modifying of the given file. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOENT no such file or directory not found + + @see FileStatus + */ + + inline static RC setTime( + const ::rtl::OUString& ustrFileURL, + const TimeValue& rCreationTime, + const TimeValue& rLastAccessTime, + const TimeValue& rLastWriteTime ) + { + return (RC) osl_setFileTime( + ustrFileURL.pData, + &rCreationTime, + &rLastAccessTime, + &rLastWriteTime ); + } + + friend class DirectoryItem; +}; + +// ----------------------------------------------------------------------------- +/** The directory item class object provides access to file status information. + + @see FileStatus + */ + +class DirectoryItem: public FileBase +{ + oslDirectoryItem _pData; + +public: + + /** Constructor. + */ + + DirectoryItem(): _pData( NULL ) + { + } + + /** Copy constructor. + */ + + DirectoryItem( const DirectoryItem& rItem ): _pData( rItem._pData) + { + if( _pData ) + osl_acquireDirectoryItem( _pData ); + } + + /** Destructor. + */ + + ~DirectoryItem() + { + if( _pData ) + osl_releaseDirectoryItem( _pData ); + } + + /** Assignment operator. + */ + + DirectoryItem& operator=(const DirectoryItem& rItem ) + { + if (&rItem != this) + { + if( _pData ) + osl_releaseDirectoryItem( _pData ); + + _pData = rItem._pData; + + if( _pData ) + osl_acquireDirectoryItem( _pData ); + } + return *this; + } + + /** Check for validity of this instance. + + @return + sal_True if object is valid directory item else sal_False. + */ + + inline sal_Bool is() + { + return _pData != NULL; + } + + /** Retrieve a single directory item. + + Retrieves a single directory item. The returned handle has an initial refcount of 1. + Due to performance issues it is not recommended to use this function while + enumerating the contents of a directory. In this case use osl_getNextDirectoryItem() instead. + + @param ustrFileURL [in] + An absolute file URL. + + @param rItem [out] + On success it receives a handle which can be used for subsequent calls to osl_getFileStatus(). + The handle has to be released by a call to osl_releaseDirectoryItem(). + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_ACCES permission denied + E_MFILE too many open files used by the process + E_NFILE too many open files in the system + E_NOENT no such file or directory + E_LOOP too many symbolic links encountered + E_NAMETOOLONG the file name is too long + E_NOTDIR a component of the path prefix of path is not a directory + E_IO on I/O errors + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + E_FAULT bad address + E_INTR the function call was interrupted + + @see FileStatus + @see Directory::getNextItem() + */ + + static inline RC get( const ::rtl::OUString& ustrFileURL, DirectoryItem& rItem ) + { + if( rItem._pData) + { + osl_releaseDirectoryItem( rItem._pData ); + rItem._pData = NULL; + } + + return (RC) osl_getDirectoryItem( ustrFileURL.pData, &rItem._pData ); + } + + /** Retrieve information about a single file or directory. + + @param rStatus [in|out] + Reference to a class which receives the information of the file or directory + represented by this directory item. + + @return + E_None on success + E_NOMEM not enough memory for allocating structures + E_INVAL the format of the parameters was not valid + E_LOOP too many symbolic links encountered + E_ACCES permission denied + E_NOENT no such file or directory + E_NAMETOOLONG file name too long + E_BADF invalid oslDirectoryItem parameter + E_FAULT bad address + E_OVERFLOW value too large for defined data type + E_INTR function call was interrupted + E_NOLINK link has been severed + E_MULTIHOP components of path require hopping to multiple remote machines and the file system does not allow it + E_MFILE too many open files used by the process + E_NFILE too many open files in the system + E_NOSPC no space left on device + E_NXIO no such device or address + E_IO on I/O errors + E_NOSYS function not implemented + + @see get() + @see Directory::getNextItem() + @see FileStatus + */ + + inline RC getFileStatus( FileStatus& rStatus ) + { + return (RC) osl_getFileStatus( _pData, &rStatus._aStatus, rStatus._nMask ); + } + +/** Determine if a directory item point the same underlying file + + The comparison is done first by URL, and then by resolving links to + find the target, and finally by comparing inodes on unix. + + @param[in] pOther + A directory handle to compare with the underlying object's item + + @return + sal_True: if the items point to an identical resource<br> + sal_False: if the items point to a different resource, or a fatal error occured<br> + + @see osl_getDirectoryItem() + + @since LibreOffice 3.6 +*/ + inline sal_Bool isIdenticalTo( const DirectoryItem &pOther ) + { + return osl_identicalDirectoryItem( _pData, pOther._pData ); + } + + friend class Directory; +}; + +//########################################### + +/** Base class for observers of directory creation notifications. + + Clients which uses the method createDirectoryPath of the class + Directory may want to be informed about the directories that + have been created. This may be accomplished by deriving from + this base class and overwriting the virtual function + DirectoryCreated. + + @see Directory::createPath +*/ +class DirectoryCreationObserver +{ +public: + virtual ~DirectoryCreationObserver() {} + + /** This method will be called when a new directory has been + created and needs to be overwritten by derived classes. + You must not delete the directory that was just created + otherwise you will run into an endless loop. + + @param aDirectoryUrl + [in]The absolute file URL of the directory that was just created by + ::osl::Directory::createPath. + */ + virtual void DirectoryCreated(const rtl::OUString& aDirectoryUrl) = 0; +}; + +//########################################### +// This just an internal helper function for +// private use. +extern "C" inline void SAL_CALL onDirectoryCreated(void* pData, rtl_uString* aDirectoryUrl) +{ + (static_cast<DirectoryCreationObserver*>(pData))->DirectoryCreated(aDirectoryUrl); +} + +/** The directory class object provides a enumeration of DirectoryItems. + + @see DirectoryItem + @see File + */ + +class Directory: public FileBase +{ + oslDirectory _pData; + ::rtl::OUString _aPath; + + /** Copy constructor. + */ + + Directory( Directory& ); + + /** Assignment operator. + */ + + Directory& operator = ( Directory& ); + +public: + + /** Constructor. + + @param strPath [in] + The full qualified URL of the directory. + Relative URLs are not allowed. + */ + + Directory( const ::rtl::OUString& strPath ): _pData( 0 ), _aPath( strPath ) + { + } + + /** Destructor. + */ + + ~Directory() + { + close(); + } + + /** Obtain the URL. + + @return + the URL with which this Directory instance was created. + + @since LibreOffice 4.1 + */ + inline rtl::OUString getURL() const { return _aPath; } + + /** Open a directory for enumerating its contents. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOENT the specified path doesn't exist + E_NOTDIR the specified path is not an directory + E_NOMEM not enough memory for allocating structures + E_ACCES permission denied + E_MFILE too many open files used by the process + E_NFILE too many open files in the system + E_NAMETOOLONG File name too long + E_LOOP Too many symbolic links encountered + + @see getNextItem() + @see close() + */ + + inline RC open() + { + return (RC) osl_openDirectory( _aPath.pData, &_pData ); + } + + /** Query if directory is open. + + Query if directory is open and so item enumeration is valid. + + @return + sal_True if the directory is open else sal_False. + + @see open() + @see close() + */ + + inline sal_Bool isOpen() { return _pData != NULL; } + + /** Close a directory. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_BADF invalid oslDirectory parameter + E_INTR the function call was interrupted + + @see open() + */ + + inline RC close() + { + oslFileError Error = osl_File_E_BADF; + + if( _pData ) + { + Error=osl_closeDirectory( _pData ); + _pData = NULL; + } + + return (RC) Error; + } + + + /** Resets the directory item enumeration to the beginning. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOENT the specified path doesn't exist + E_NOTDIR the specified path is not an directory + E_NOMEM not enough memory for allocating structures + E_ACCES permission denied + E_MFILE too many open files used by the process + E_NFILE too many open files in the system + E_NAMETOOLONG File name too long + E_LOOP Too many symbolic links encountered + + @see open() + */ + + inline RC reset() + { + close(); + return open(); + } + + /** Retrieve the next item of a previously opened directory. + + Retrieves the next item of a previously opened directory. + + @param rItem [out] + On success a valid DirectoryItem. + + @param nHint [in] + With this parameter the caller can tell the implementation that (s)he + is going to call this function uHint times afterwards. This enables the implementation to + get the information for more than one file and cache it until the next calls. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_NOENT no more entries in this directory + E_BADF invalid oslDirectory parameter + E_OVERFLOW the value too large for defined data type + + @see DirectoryItem + */ + + inline RC getNextItem( DirectoryItem& rItem, sal_uInt32 nHint = 0 ) + { + if( rItem._pData ) + { + osl_releaseDirectoryItem( rItem._pData ); + rItem._pData = 0; + } + return ( RC) osl_getNextDirectoryItem( _pData, &rItem._pData, nHint ); + } + + + /** Retrieve information about a volume. + + Retrieves information about a volume. A volume can either be a mount point, a network + resource or a drive depending on Operating System and File System. + + @param ustrDirectoryURL [in] + Full qualified URL of the volume + + @param rInfo [out] + On success it receives information about the volume. + + @return + E_None on success + E_NOMEM not enough memory for allocating structures + E_INVAL the format of the parameters was not valid + E_NOTDIR not a directory + E_NAMETOOLONG file name too long + E_NOENT no such file or directory + E_ACCES permission denied + E_LOOP too many symbolic links encountered + E_FAULT Bad address + E_IO on I/O errors + E_NOSYS function not implemented + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + E_INTR function call was interrupted + + @see FileStatus + @see VolumeInfo + */ + + inline static RC getVolumeInfo( const ::rtl::OUString& ustrDirectoryURL, VolumeInfo& rInfo ) + { + return (RC) osl_getVolumeInformation( ustrDirectoryURL.pData, &rInfo._aInfo, rInfo._nMask ); + } + + /** Create a directory. + + @param ustrDirectoryURL [in] + Full qualified URL of the directory to create. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_EXIST file exists + E_ACCES permission denied + E_NAMETOOLONG file name too long + E_NOENT no such file or directory + E_NOTDIR not a directory + E_ROFS read-only file system + E_NOSPC no space left on device + E_DQUOT quota exceeded + E_LOOP too many symbolic links encountered + E_FAULT bad address + E_IO on I/O errors + E_MLINK too many links + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + + @see remove() + */ + + inline static RC create( const ::rtl::OUString& ustrDirectoryURL ) + { + return (RC) osl_createDirectory( ustrDirectoryURL.pData ); + } + + /** Remove an empty directory. + + @param ustrDirectoryURL [in] + Full qualified URL of the directory. + + @return + E_None on success + E_INVAL the format of the parameters was not valid + E_NOMEM not enough memory for allocating structures + E_PERM operation not permitted + E_ACCES permission denied + E_NOENT no such file or directory + E_NOTDIR not a directory + E_NOTEMPTY directory not empty + E_FAULT bad address + E_NAMETOOLONG file name too long + E_BUSY device or resource busy + E_ROFS read-only file system + E_LOOP too many symbolic links encountered + E_BUSY device or resource busy + E_EXIST file exists + E_IO on I/O errors + E_MULTIHOP multihop attempted + E_NOLINK link has been severed + + @see create() + */ + + inline static RC remove( const ::rtl::OUString& ustrDirectoryURL ) + { + return (RC) osl_removeDirectory( ustrDirectoryURL.pData ); + } + + /** Create a directory path. + + The osl_createDirectoryPath function creates a specified directory path. + All nonexisting sub directories will be created. + <p><strong>PLEASE NOTE:</strong> You cannot rely on getting the error code + E_EXIST for existing directories. Programming against this error code is + in general a strong indication of a wrong usage of osl_createDirectoryPath.</p> + + @param aDirectoryUrl + [in] The absolute file URL of the directory path to create. + A relative file URL will not be accepted. + + @param aDirectoryCreationObserver + [in] Pointer to an instance of type DirectoryCreationObserver that will + be informed about the creation of a directory. The value of this + parameter may be NULL, in this case notifications will not be sent. + + @return + <dl> + <dt>E_None</dt> + <dd>On success</dd> + <dt>E_INVAL</dt> + <dd>The format of the parameters was not valid</dd> + <dt>E_ACCES</dt> + <dd>Permission denied</dd> + <dt>E_EXIST</dt> + <dd>The final node of the specified directory path already exist</dd> + <dt>E_NAMETOOLONG</dt> + <dd>The name of the specified directory path exceeds the maximum allowed length</dd> + <dt>E_NOTDIR</dt> + <dd>A component of the specified directory path already exist as file in any part of the directory path</dd> + <dt>E_ROFS</dt> + <dd>Read-only file system</dd> + <dt>E_NOSPC</dt> + <dd>No space left on device</dd> + <dt>E_DQUOT</dt> + <dd>Quota exceeded</dd> + <dt>E_FAULT</dt> + <dd>Bad address</dd> + <dt>E_IO</dt> + <dd>I/O error</dd> + <dt>E_LOOP</dt> + <dd>Too many symbolic links encountered</dd> + <dt>E_NOLINK</dt> + <dd>Link has been severed</dd> + <dt>E_invalidError</dt> + <dd>An unknown error occurred</dd> + </dl> + + @see DirectoryCreationObserver + @see create + */ + static RC createPath( + const ::rtl::OUString& aDirectoryUrl, + DirectoryCreationObserver* aDirectoryCreationObserver = NULL) + { + return (RC)osl_createDirectoryPath( + aDirectoryUrl.pData, + (aDirectoryCreationObserver) ? onDirectoryCreated : NULL, + aDirectoryCreationObserver); + } +}; + +} /* namespace osl */ + +#endif /* _OSL_FILE_HXX_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/getglobalmutex.hxx b/include/osl/getglobalmutex.hxx new file mode 100644 index 000000000000..4fbd32a3e4b5 --- /dev/null +++ b/include/osl/getglobalmutex.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OSL_GETGLOBALMUTEX_HXX +#define INCLUDED_OSL_GETGLOBALMUTEX_HXX + +#include "osl/mutex.hxx" + +namespace osl { + +/** A helper functor for the rtl_Instance template. + + See the rtl_Instance template for examples of how this class is used. + */ +class GetGlobalMutex +{ +public: + ::osl::Mutex * operator()() + { + return ::osl::Mutex::getGlobalMutex(); + } +}; + +} + +#endif // INCLUDED_OSL_GETGLOBALMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/interlck.h b/include/osl/interlck.h new file mode 100644 index 000000000000..31212deed274 --- /dev/null +++ b/include/osl/interlck.h @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_INTERLOCK_H_ +#define _OSL_INTERLOCK_H_ + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef sal_Int32 oslInterlockedCount; + +/** Increments the count variable addressed by pCount. + @param pCount Address of count variable + @return The adjusted value of the count variable. +*/ +SAL_DLLPUBLIC oslInterlockedCount SAL_CALL osl_incrementInterlockedCount(oslInterlockedCount* pCount); + +/** Decrement the count variable addressed by pCount. + @param pCount Address of count variable + @return The adjusted value of the count variable. +*/ +SAL_DLLPUBLIC oslInterlockedCount SAL_CALL osl_decrementInterlockedCount(oslInterlockedCount* pCount); + + +/// @cond INTERNAL + +/** Increments the count variable addressed by p. + + @attention This functionality should only be used internally within + LibreOffice. + + @param p Address of count variable + @return The adjusted value of the count variable. + + @since LibreOffice 4.0 +*/ +#if HAVE_GCC_BUILTIN_ATOMIC +# define osl_atomic_increment(p) __sync_add_and_fetch((p), 1) +#else +# define osl_atomic_increment(p) osl_incrementInterlockedCount((p)) +#endif + + +/** Decrement the count variable addressed by p. + + @attention This functionality should only be used internally within + LibreOffice. + + @param p Address of count variable + @return The adjusted value of the count variable. + + @since LibreOffice 4.0 +*/ +#if HAVE_GCC_BUILTIN_ATOMIC +# define osl_atomic_decrement(p) __sync_sub_and_fetch((p), 1) +#else +# define osl_atomic_decrement(p) osl_decrementInterlockedCount((p)) +#endif + +/// @endcond + +#ifdef __cplusplus +} +#endif + + +#endif /* _OSL_INTERLOCK_H_ */ + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/module.h b/include/osl/module.h new file mode 100644 index 000000000000..09f2b17b401c --- /dev/null +++ b/include/osl/module.h @@ -0,0 +1,251 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_MODULE_H_ +#define _OSL_MODULE_H_ + +#include "sal/config.h" + +#include "rtl/tencinfo.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SAL_DLLPREFIX +#define SAL_MODULENAME(name) SAL_DLLPREFIX name SAL_DLLEXTENSION +#else +#define SAL_MODULENAME(name) name SAL_DLLEXTENSION +#endif + +#if defined(SAL_W32) +#define SAL_MODULENAME_WITH_VERSION(name, version) name version SAL_DLLEXTENSION + +#elif defined(SAL_UNX) +#if defined(MACOSX) +#define SAL_MODULENAME_WITH_VERSION(name, version) SAL_DLLPREFIX name ".dylib." version +#else +#define SAL_MODULENAME_WITH_VERSION(name, version) SAL_DLLPREFIX name SAL_DLLEXTENSION "." version +#endif + +#endif + +#define SAL_LOADMODULE_DEFAULT 0x00000 +#define SAL_LOADMODULE_LAZY 0x00001 +#define SAL_LOADMODULE_NOW 0x00002 +#define SAL_LOADMODULE_GLOBAL 0x00100 + +typedef void* oslModule; + +/** Generic Function pointer type that will be used as symbol address. + @see osl_getFunctionSymbol. + @see osl_getModuleURLFromFunctionAddress. +*/ +typedef void ( SAL_CALL *oslGenericFunction )( void ); + +#ifndef DISABLE_DYNLOADING + +/** Load a shared library or module. + @param strModuleName denotes the name of the module to be loaded. + @param nRtldMode denotes the mode. + @return NULL if the module could not be loaded, otherwise a handle to the module. +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModule(rtl_uString *strModuleName, sal_Int32 nRtldMode); + +/** Load a shared library or module. + @param pModuleName denotes the name of the module to be loaded. + @param nRtldMode denotes the mode. + @return NULL if the module could not be loaded, otherwise a handle to the module. + @since UDK 3.6 +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModuleAscii(const sal_Char *pModuleName, sal_Int32 nRtldMode); + +/** Load a module located relative to some other module. + + @param baseModule + must point to a function that is part of the code of some loaded module; + must not be NULL. + + @param relativePath + a relative URL; must not be NULL. + + @param mode + the SAL_LOADMODULE_xxx flags. + + @return + a non-NULL handle to the loaded module, or NULL if an error occurred. + + @since UDK 3.2.8 +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModuleRelative( + oslGenericFunction baseModule, rtl_uString * relativePath, sal_Int32 mode); + +/** Load a module located relative to some other module. + + @param baseModule + must point to a function that is part of the code of some loaded module; + must not be NULL. + + @param relativePath + a relative URL containing only ASCII (0x01--7F) characters; must not be + NULL. + + @param mode + the SAL_LOADMODULE_xxx flags. + + @return + a non-NULL handle to the loaded module, or NULL if an error occurred. + + @since LibreOffice 3.5 +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModuleRelativeAscii( + oslGenericFunction baseModule, char const * relativePath, sal_Int32 mode); + /* This function is guaranteed not to call into + FullTextEncodingDataSingleton in sal/textenc/textenc.cxx, so can be used + in its implementation without running into circles. */ + +#endif + +/** Retrieve the handle of an already loaded module. + + This function can be used to search for a function symbol in the process address space. + Do not use the returned handle as an argument to osl_unloadModule. On Unix platforms, + pModuleName gets ignored and the special handle RTLD_DEFAULT is returned. + + @param pModuleName + [in] denotes the name of the module to search for. Ignored on Unix + + @param pResult + [out] a pointer to a oslModule that is updated with the requested module handle + on success. + + @return + sal_True if the module handle could be retrieved and has been copied to *pResult. + sal_False if the module has not been loaded yet. + + @see osl_getFunctionSymbol + @see osl_getAsciiFunctionSymbol +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getModuleHandle(rtl_uString *pModuleName, oslModule *pResult); + +#ifndef DISABLE_DYNLOADING + +/** Release the module +*/ +SAL_DLLPUBLIC void SAL_CALL osl_unloadModule(oslModule Module); + +#endif + +/** lookup the specified symbol name. + @return address of the symbol or NULL if lookup failed. +*/ +SAL_DLLPUBLIC void* SAL_CALL osl_getSymbol( oslModule Module, rtl_uString *strSymbolName); + +/** Lookup the specified function symbol name. + + osl_getFunctionSymbol is an alternative function for osl_getSymbol. + Use Function pointer as symbol address to conceal type conversion. + + @param Module + [in] the handle of the Module. + + @param ustrFunctionSymbolName + [in] Name of the function that will be looked up. + + @return + <dl> + <dt>Function address.</dt> + <dd>on success</dd> + <dt>NULL</dt> + <dd>lookup failed or the parameter are invalid.</dd> + </dl> + + @see osl_getSymbol + @see osl_getAsciiFunctionSymbol +*/ +SAL_DLLPUBLIC oslGenericFunction SAL_CALL osl_getFunctionSymbol( + oslModule Module, rtl_uString *ustrFunctionSymbolName ); + +/** Lookup the specified function symbol name. + + osl_getAsciiFunctionSymbol is an alternative function for osl_getFunctionSymbol. + It expects the C-style function name string to contain ascii characters only. + + @param Module + [in] a module handle as returned by osl_loadModule or osl_getModuleHandle + + @param pSymbol + [in] Name of the function that will be looked up. + + @return + <dl> + <dt>Function address.</dt> + <dd>on success</dd> + <dt>NULL</dt> + <dd>lookup failed or the parameter are invalid.</dd> + </dl> + + @see osl_getModuleHandle + @see osl_getFunctionSymbol +*/ +SAL_DLLPUBLIC oslGenericFunction SAL_CALL osl_getAsciiFunctionSymbol( + oslModule Module, const sal_Char *pSymbol ); + + +/** Lookup URL of module which is mapped at the specified address. + @param pv specifies an address in the process memory space. + @param pustrURL receives the URL of the module that is mapped at pv. + @return sal_True on success, sal_False if no module can be found at the specified address. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getModuleURLFromAddress( + void *pv, rtl_uString **pustrURL ); + +/** Lookup URL of module which is mapped at the specified function address. + + osl_getModuleURLFromFunctionAddress is an alternative function for osl_getModuleURLFromAddress. + Use Function pointer as symbol address to conceal type conversion. + + @param pf + [in] function address in oslGenericFunction format. + + @param pustrFunctionURL + [out] receives the URL of the module that is mapped at pf. + + @return + <dl> + <dt>sal_True</dt> + <dd>on success</dd> + <dt>sal_False</dt> + <dd>no module can be found at the specified function address or parameter is somewhat invalid.</dd> + </dl> + + @see osl_getModuleURLFromAddress +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getModuleURLFromFunctionAddress( + oslGenericFunction pf, rtl_uString **pustrFunctionURL ); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_MODULE_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/module.hxx b/include/osl/module.hxx new file mode 100644 index 000000000000..317579dc816b --- /dev/null +++ b/include/osl/module.hxx @@ -0,0 +1,175 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_MODULE_HXX_ +#define _OSL_MODULE_HXX_ + +#include <rtl/ustring.hxx> +#include <osl/module.h> + +namespace osl +{ + +class Module +{ + Module( const Module&); + Module& operator = ( const Module&); + +public: + static sal_Bool getUrlFromAddress(void * addr, ::rtl::OUString & libraryUrl) { + return osl_getModuleURLFromAddress(addr, &libraryUrl.pData); + } + + /** Get module URL from the specified function address in the module. + + Similar to getUrlFromAddress, but use a function address to get URL of the Module. + Use Function pointer as symbol address to conceal type conversion. + + @param addr + [in] function address in oslGenericFunction format. + + @param libraryUrl + [in|out] receives the URL of the module. + + @return + <dl> + <dt>sal_True</dt> + <dd>on success</dd> + <dt>sal_False</dt> + <dd>can not get the URL from the specified function address or the parameter is invalid.</dd> + </dl> + + @see getUrlFromAddress + */ + static sal_Bool getUrlFromAddress( oslGenericFunction addr, ::rtl::OUString & libraryUrl){ + return osl_getModuleURLFromFunctionAddress( addr, &libraryUrl.pData ); + } + + Module(): m_Module(0){} + +#ifndef DISABLE_DYNLOADING + + Module( const ::rtl::OUString& strModuleName, sal_Int32 nRtldMode = SAL_LOADMODULE_DEFAULT) : m_Module(0) + { + load( strModuleName, nRtldMode); + } + +#endif + + ~Module() + { +#ifndef DISABLE_DYNLOADING + osl_unloadModule(m_Module); +#endif + } + +#ifndef DISABLE_DYNLOADING + + sal_Bool SAL_CALL load( const ::rtl::OUString& strModuleName, + sal_Int32 nRtldMode = SAL_LOADMODULE_DEFAULT) + { + unload(); + m_Module= osl_loadModule( strModuleName.pData, nRtldMode ); + return is(); + } + + /// @since UDK 3.2.8 + sal_Bool SAL_CALL loadRelative( + ::oslGenericFunction baseModule, ::rtl::OUString const & relativePath, + ::sal_Int32 mode = SAL_LOADMODULE_DEFAULT) + { + unload(); + m_Module = osl_loadModuleRelative(baseModule, relativePath.pData, mode); + return is(); + } + + /// @since LibreOffice 3.5 + sal_Bool SAL_CALL loadRelative( + oslGenericFunction baseModule, char const * relativePath, + sal_Int32 mode = SAL_LOADMODULE_DEFAULT) + { + unload(); + m_Module = osl_loadModuleRelativeAscii(baseModule, relativePath, mode); + return is(); + } + + void SAL_CALL unload() + { + if (m_Module) + { + osl_unloadModule(m_Module); + m_Module = 0; + } + } + +#endif + + sal_Bool SAL_CALL is() const + { + return m_Module != NULL; + } + + void* SAL_CALL getSymbol( const ::rtl::OUString& strSymbolName) + { + return ( osl_getSymbol( m_Module, strSymbolName.pData ) ); + } + + /** Get function address by the function name in the module. + + getFunctionSymbol is an alternative function for getSymbol. + Use Function pointer as symbol address to conceal type conversion. + + @param ustrFunctionSymbolName + [in] Function name to be looked up. + + @return + <dl> + <dt>oslGenericFunction format function address</dt> + <dd>on success</dd> + <dt>NULL</dt> + <dd>lookup failed or parameter is somewhat invalid</dd> + </dl> + + @see getSymbol + */ + oslGenericFunction SAL_CALL getFunctionSymbol( const ::rtl::OUString& ustrFunctionSymbolName ) const + { + return ( osl_getFunctionSymbol( m_Module, ustrFunctionSymbolName.pData ) ); + } + + /// @since LibreOffice 3.5 + oslGenericFunction SAL_CALL getFunctionSymbol(char const * name) const { + return osl_getAsciiFunctionSymbol(m_Module, name); + } + + operator oslModule() const + { + return m_Module; + } + +private: + oslModule m_Module; + +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/mutex.h b/include/osl/mutex.h new file mode 100644 index 000000000000..1336d4fcea95 --- /dev/null +++ b/include/osl/mutex.h @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_MUTEX_H_ +#define _OSL_MUTEX_H_ + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _oslMutexImpl; +typedef struct _oslMutexImpl * oslMutex; + +/** Create a thread-local mutex. + @return 0 if the mutex could not be created, otherwise a handle to the mutex. +*/ +SAL_DLLPUBLIC oslMutex SAL_CALL osl_createMutex(void); + +/** Release the OS-structures and free mutex data-structure. + @param Mutex the mutex-handle +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyMutex(oslMutex Mutex); + +/** Acquire the mutex, block if already acquired by another thread. + @param Mutex handle to a created mutex. + @return False if system-call fails. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_acquireMutex(oslMutex Mutex); + +/** Try to acquire the mutex without blocking. + @param Mutex handle to a created mutex. + @return False if it could not be acquired. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_tryToAcquireMutex(oslMutex Mutex); + +/** Release the mutex. + @param Mutex handle to a created mutex. + @return False if system-call fails. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_releaseMutex(oslMutex Mutex); + +/** Returns a unique and global mutex. + @return the global mutex. +*/ +SAL_DLLPUBLIC oslMutex * SAL_CALL osl_getGlobalMutex(void); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_MUTEX_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/mutex.hxx b/include/osl/mutex.hxx new file mode 100644 index 000000000000..18ff44444223 --- /dev/null +++ b/include/osl/mutex.hxx @@ -0,0 +1,272 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_MUTEX_HXX_ +#define _OSL_MUTEX_HXX_ + +#ifdef __cplusplus + +#include <osl/mutex.h> + + +namespace osl +{ + /** A mutual exclusion synchronization object + */ + class SAL_WARN_UNUSED Mutex { + + public: + /** Create a thread-local mutex. + @return 0 if the mutex could not be created, otherwise a handle to the mutex. + @see ::osl_createMutex() + */ + Mutex() + { + mutex = osl_createMutex(); + } + + /** Release the OS-structures and free mutex data-structure. + @see ::osl_destroyMutex() + */ + ~Mutex() + { + osl_destroyMutex(mutex); + } + + /** Acquire the mutex, block if already acquired by another thread. + @return sal_False if system-call fails. + @see ::osl_acquireMutex() + */ + sal_Bool acquire() + { + return osl_acquireMutex(mutex); + } + + /** Try to acquire the mutex without blocking. + @return sal_False if it could not be acquired. + @see ::osl_tryToAcquireMutex() + */ + sal_Bool tryToAcquire() + { + return osl_tryToAcquireMutex(mutex); + } + + /** Release the mutex. + @return sal_False if system-call fails. + @see ::osl_releaseMutex() + */ + sal_Bool release() + { + return osl_releaseMutex(mutex); + } + + /** Returns a global static mutex object. + The global and static mutex object can be used to initialize other + static objects in a thread safe manner. + @return the global mutex object + @see ::osl_getGlobalMutex() + */ + static Mutex * getGlobalMutex() + { + return (Mutex *)osl_getGlobalMutex(); + } + + private: + oslMutex mutex; + + /** The underlying oslMutex has no reference count. + + Since the underlying oslMutex is not a reference counted object, copy + constructed Mutex may work on an already destructed oslMutex object. + + */ + Mutex(const Mutex&); + + /** The underlying oslMutex has no reference count. + + When destructed, the Mutex object destroys the undelying oslMutex, + which might cause severe problems in case it's a temporary object. + + */ + Mutex(oslMutex Mutex); + + /** This assignment operator is private for the same reason as + the copy constructor. + */ + Mutex& operator= (const Mutex&); + + /** This assignment operator is private for the same reason as + the constructor taking a oslMutex argument. + */ + Mutex& operator= (oslMutex); + }; + + /** A helper class for mutex objects and interfaces. + */ + template<class T> + class Guard + { + private: + Guard( const Guard& ); + const Guard& operator = ( const Guard& ); + + protected: + T * pT; + public: + + /** Acquires the object specified as parameter. + */ + Guard(T * pT_) : pT(pT_) + { + pT->acquire(); + } + + /** Acquires the object specified as parameter. + */ + Guard(T & t) : pT(&t) + { + pT->acquire(); + } + + /** Releases the mutex or interface. */ + ~Guard() + { + pT->release(); + } + }; + + /** A helper class for mutex objects and interfaces. + */ + template<class T> + class ClearableGuard + { + private: + ClearableGuard( const ClearableGuard& ); + const ClearableGuard& operator = ( const ClearableGuard& ); + protected: + T * pT; + public: + + /** Acquires the object specified as parameter. + */ + ClearableGuard(T * pT_) : pT(pT_) + { + pT->acquire(); + } + + /** Acquires the object specified as parameter. + */ + ClearableGuard(T & t) : pT(&t) + { + pT->acquire(); + } + + /** Releases the mutex or interface if not already released by clear(). + */ + ~ClearableGuard() + { + if (pT) + pT->release(); + } + + /** Releases the mutex or interface. + */ + void clear() + { + if(pT) + { + pT->release(); + pT = NULL; + } + } + }; + + /** A helper class for mutex objects and interfaces. + */ + template< class T > + class ResettableGuard : public ClearableGuard< T > + { + private: + ResettableGuard(ResettableGuard &); // not defined + void operator =(ResettableGuard &); // not defined + + protected: + T* pResetT; + public: + /** Acquires the object specified as parameter. + */ + ResettableGuard( T* pT_ ) : + ClearableGuard<T>( pT_ ), + pResetT( pT_ ) + {} + + /** Acquires the object specified as parameter. + */ + ResettableGuard( T& rT ) : + ClearableGuard<T>( rT ), + pResetT( &rT ) + {} + + /** Re-aquires the mutex or interface. + */ + void reset() + { + if( pResetT ) + { + this->pT = pResetT; + this->pT->acquire(); + } + } + }; + + typedef Guard<Mutex> MutexGuard; + typedef ClearableGuard<Mutex> ClearableMutexGuard; + typedef ResettableGuard< Mutex > ResettableMutexGuard; + + /** SolarMutex interface, needed for SolarMutex. + Deprecated, used just for Application::GetSolarMutex(). + */ + class SolarMutex + { + public: + /** Blocks if mutex is already in use + */ + virtual void SAL_CALL acquire() = 0; + + /** Tries to get the mutex without blocking. + */ + virtual sal_Bool SAL_CALL tryToAcquire() = 0; + + /** Releases the mutex. + */ + virtual void SAL_CALL release() = 0; + + protected: + SolarMutex() {} + virtual ~SolarMutex() {} + }; + typedef osl::Guard< SolarMutex > SolarGuard; + typedef osl::ClearableGuard< SolarMutex > ClearableSolarGuard; + typedef osl::ResettableGuard< SolarMutex > ResettableSolarGuard; +} + +#endif /* __cplusplus */ +#endif /* _OSL_MUTEX_HXX_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/nlsupport.h b/include/osl/nlsupport.h new file mode 100644 index 000000000000..9af93d9237ec --- /dev/null +++ b/include/osl/nlsupport.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef _OSL_NLSUPPORT_H_ +#define _OSL_NLSUPPORT_H_ + +#include "sal/config.h" + +#include "rtl/locale.h" +#include "rtl/textenc.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Determines the text encoding used by the underlying platform for the + specified locale. + + @param pLocale + the locale to return the text encoding for. If this parameter is NULL, + the default locale of the current process is used. + + @returns the rtl_TextEncoding that matches the platform specific encoding + description or RTL_TEXTENCODING_DONTKNOW if no mapping is available. +*/ + +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL osl_getTextEncodingFromLocale( + rtl_Locale * pLocale ); + + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_NLSUPPORT_H_ */ + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/pipe.h b/include/osl/pipe.h new file mode 100644 index 000000000000..52ba8b9813e6 --- /dev/null +++ b/include/osl/pipe.h @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef _OSL_PIPE_H_ +#define _OSL_PIPE_H_ + +#include "sal/config.h" + +#include "osl/security.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + osl_Pipe_E_None, /* no error */ + osl_Pipe_E_NotFound, /* Pipe could not be found */ + osl_Pipe_E_AlreadyExists, /* Pipe already exists */ + osl_Pipe_E_NoProtocol, /* Protocol not available */ + osl_Pipe_E_NetworkReset, /* Network dropped connection because of reset */ + osl_Pipe_E_ConnectionAbort, /* Software caused connection abort */ + osl_Pipe_E_ConnectionReset, /* Connection reset by peer */ + osl_Pipe_E_NoBufferSpace, /* No buffer space available */ + osl_Pipe_E_TimedOut, /* Connection timed out */ + osl_Pipe_E_ConnectionRefused, /* Connection refused */ + osl_Pipe_E_invalidError, /* unmapped error: always last entry in enum! */ + osl_Pipe_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslPipeError; + +typedef sal_uInt32 oslPipeOptions; +#define osl_Pipe_OPEN 0x0000 /* open existing pipe */ +#define osl_Pipe_CREATE 0x0001 /* create pipe and open it, fails if already existst */ + +typedef struct oslPipeImpl * oslPipe; + +/** + */ +SAL_DLLPUBLIC oslPipe SAL_CALL osl_createPipe( + rtl_uString *strPipeName, oslPipeOptions Options, oslSecurity Security); + +/** decreases the refcount of the pipe. + If the refcount drops to zero, the handle is destroyed. + */ +SAL_DLLPUBLIC void SAL_CALL osl_releasePipe( oslPipe ); + +/** increases the refcount of the pipe. + */ +SAL_DLLPUBLIC void SAL_CALL osl_acquirePipe( oslPipe Pipe ); + +/** closes the pipe, any read,write or accept actions stop immeadiatly. + */ +SAL_DLLPUBLIC void SAL_CALL osl_closePipe( oslPipe ); + + +SAL_DLLPUBLIC oslPipe SAL_CALL osl_acceptPipe(oslPipe Pipe); + +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_sendPipe(oslPipe Pipe, const void* pBuffer, sal_Int32 BufferSize); +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_receivePipe(oslPipe Pipe, void* pBuffer, sal_Int32 BufferSize); + +/** Reads blocking from the pipe. + @return Number of read bytes. If less than BufferSize, the pipe was closed. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_readPipe( oslPipe Pipe, void *pBuffer, sal_Int32 BufferSize ); + +/** Writes blocking onto the pipe. + @return Number of written bytes. If less than BufferSize, the pipe was closed. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_writePipe( oslPipe Pipe, const void *pBuffer, sal_Int32 BufferSize ); + +SAL_DLLPUBLIC oslPipeError SAL_CALL osl_getLastPipeError(oslPipe Pipe); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_PIPE_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/pipe.hxx b/include/osl/pipe.hxx new file mode 100644 index 000000000000..906ca8b08fb8 --- /dev/null +++ b/include/osl/pipe.hxx @@ -0,0 +1,206 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef _OSL_PIPE_HXX_ +#define _OSL_PIPE_HXX_ + +#include <osl/pipe_decl.hxx> + +namespace osl +{ + //______________________________________________________________________________ + inline Pipe::Pipe() + : m_handle( 0 ) + {} + + //______________________________________________________________________________ + inline Pipe::Pipe(const ::rtl::OUString& strName, oslPipeOptions Options ) + : m_handle( osl_createPipe( strName.pData, Options , 0 ) ) + {} + + //______________________________________________________________________________ + inline Pipe::Pipe(const ::rtl::OUString& strName, oslPipeOptions Options,const Security & rSecurity) + : m_handle( osl_createPipe( strName.pData, Options , rSecurity.getHandle() ) ) + {} + + //______________________________________________________________________________ + inline Pipe::Pipe(const Pipe& pipe ) + : m_handle( pipe.m_handle ) + { + if( m_handle ) + osl_acquirePipe( m_handle ); + } + + //______________________________________________________________________________ + inline Pipe::Pipe( oslPipe pipe, __sal_NoAcquire ) + : m_handle ( pipe ) + {} + + //______________________________________________________________________________ + inline Pipe::Pipe(oslPipe pipe) + : m_handle( pipe ) + { + if( m_handle ) + osl_acquirePipe( m_handle ); + } + + //______________________________________________________________________________ + inline Pipe::~Pipe() + { + if( m_handle ) + osl_releasePipe( m_handle ); + } + + //______________________________________________________________________________ + inline sal_Bool Pipe::create( const ::rtl::OUString & strName, + oslPipeOptions Options, const Security &rSec ) + { + *this = Pipe( strName, Options, rSec ); + return is(); + } + + //______________________________________________________________________________ + inline sal_Bool Pipe::create( const ::rtl::OUString & strName, oslPipeOptions Options ) + { + *this = Pipe( strName, Options ); + return is(); + } + //______________________________________________________________________________ + inline Pipe& SAL_CALL Pipe::operator= (const Pipe& pipe) + { + *this = pipe.getHandle(); + return *this; + } + + //______________________________________________________________________________ + inline Pipe & SAL_CALL Pipe::operator=( oslPipe pipe) + { + if( pipe ) + osl_acquirePipe( pipe ); + if( m_handle ) + osl_releasePipe( m_handle ); + m_handle = pipe; + return *this; + } + + //______________________________________________________________________________ + inline sal_Bool SAL_CALL Pipe::is() const + { + return m_handle != 0; + } + + //______________________________________________________________________________ + inline sal_Bool SAL_CALL Pipe::operator==( const Pipe& rPipe ) const + { + return m_handle == rPipe.m_handle; + } + + //______________________________________________________________________________ + inline void SAL_CALL Pipe::close() + { + osl_closePipe( m_handle ); + } + + //______________________________________________________________________________ + inline void SAL_CALL Pipe::clear() + { + if( m_handle ) + { + osl_releasePipe( m_handle ); + m_handle = 0; + } + } + + //______________________________________________________________________________ + inline oslPipeError SAL_CALL Pipe::accept(StreamPipe& Connection) + { + Connection = StreamPipe( osl_acceptPipe( m_handle ), SAL_NO_ACQUIRE); + if( Connection.is() ) + return osl_Pipe_E_None; + else + return getError(); + } + + //______________________________________________________________________________ + inline oslPipeError SAL_CALL Pipe::getError() const + { + return osl_getLastPipeError( 0 ); + } + + //______________________________________________________________________________ + inline oslPipe SAL_CALL Pipe::getHandle() const + { + return m_handle; + } + + //______________________________________________________________________________ + inline StreamPipe::StreamPipe(){} + + //______________________________________________________________________________ + inline StreamPipe::StreamPipe(oslPipe hPipe) + : Pipe( hPipe ) + { + } + + //______________________________________________________________________________ + inline StreamPipe::StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security &rSec ) + : Pipe( strName, Options , rSec ) + {} + + //______________________________________________________________________________ + inline StreamPipe::StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options ) + : Pipe( strName, Options ) + {} + + //______________________________________________________________________________ + inline StreamPipe::StreamPipe(const StreamPipe& aPipe) + : Pipe( aPipe ) + {} + //______________________________________________________________________________ + inline StreamPipe::StreamPipe( oslPipe pipe, __sal_NoAcquire noacquire ) + : Pipe( pipe , noacquire ) + {} + + //______________________________________________________________________________ + inline sal_Int32 SAL_CALL StreamPipe::read(void* pBuffer, sal_Int32 n) const + { + return osl_readPipe( m_handle, pBuffer, n ); + } + + //______________________________________________________________________________ + inline sal_Int32 SAL_CALL StreamPipe::write(const void* pBuffer, sal_Int32 n) const + { + return osl_writePipe( m_handle, pBuffer , n ); + } + + //______________________________________________________________________________ + inline sal_Int32 SAL_CALL StreamPipe::recv(void* pBuffer, sal_Int32 BytesToRead) const + { + return osl_receivePipe( m_handle, pBuffer , BytesToRead ); + } + + //______________________________________________________________________________ + inline sal_Int32 SAL_CALL StreamPipe::send(const void* pBuffer, sal_Int32 BytesToSend) const + { + return osl_sendPipe( m_handle, pBuffer , BytesToSend ); + } + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/pipe_decl.hxx b/include/osl/pipe_decl.hxx new file mode 100644 index 000000000000..21e07952b7ff --- /dev/null +++ b/include/osl/pipe_decl.hxx @@ -0,0 +1,229 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef _OSL_PIPE_DECL_HXX_ +#define _OSL_PIPE_DECL_HXX_ + +#include <osl/pipe.h> +# include <osl/security.hxx> +#include <rtl/ustring.hxx> + +namespace osl { + +class StreamPipe; + +/** Represents a pipe. +*/ +class Pipe +{ +protected: + oslPipe m_handle; + +public: + + /** Does not create a pipe. Use assignment operator to + make this a useable pipe. + */ + inline Pipe(); + + /** Creates an insecure pipe that is accessible for all users. + @param strName + @param Options + */ + inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options); + + /** Creates a secure pipe that access depends on the umask settings. + @param strName + @param Options + @param rSecurity + */ + inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options,const Security & rSecurity); + + /** Copy constructor. + */ + inline Pipe(const Pipe& pipe); + + /** Constructs a Pipe reference without acquiring the handle + */ + inline Pipe( oslPipe pipe, __sal_NoAcquire noacquire ); + + /** Creates pipe as wrapper around the underlying oslPipe. + @param Pipe + */ + inline Pipe(oslPipe Pipe); + + /** Destructor. Destroys the underlying oslPipe. + */ + inline ~Pipe(); + + inline sal_Bool SAL_CALL is() const; + + /** Creates an insecure pipe that is accessible for all users + with the given attributes. + If the pipe was already created, the old one will be discarded. + @param strName + @param Options + @param rSec + @return True if socket was successfully created. + */ + inline sal_Bool create( const ::rtl::OUString & strName, + oslPipeOptions Options, const Security &rSec ); + + /** Creates a secure that access rights depend on the umask settings + with the given attributes. + + If socket was already created, the old one will be discarded. + @param strName + @param Options + @return True if socket was successfully created. + */ + inline sal_Bool create( const ::rtl::OUString & strName, oslPipeOptions Options = osl_Pipe_OPEN ); + + /** releases the underlying handle + */ + inline void SAL_CALL clear(); + + /** Assignment operator. If pipe was already created, the old one will + be discarded. + */ + inline Pipe& SAL_CALL operator= (const Pipe& pipe); + + /** Assignment operator. If pipe was already created, the old one will + be discarded. + */ + inline Pipe& SAL_CALL operator= (const oslPipe pipe ); + + /** Checks if the pipe is valid. + @return True if the object represents a valid pipe. + */ + inline sal_Bool SAL_CALL isValid() const; + + inline sal_Bool SAL_CALL operator==( const Pipe& rPipe ) const; + + /** Closes the pipe. + */ + inline void SAL_CALL close(); + + /** Accept connection on an existing pipe + */ + inline oslPipeError SAL_CALL accept(StreamPipe& Connection); + + + /** Delivers a constant decribing the last error for the pipe system. + @return ENONE if no error occurred, invalid_PipeError if + an unknown (unmapped) error occurred, otherwise an enum describing the + error. + */ + inline oslPipeError SAL_CALL getError() const; + + inline oslPipe SAL_CALL getHandle() const; +}; + +/** A pipe to send or receive a stream of data. +*/ +class StreamPipe : public Pipe +{ +public: + + /** Creates an unattached pipe. You must attach the pipe to an oslPipe + e.g. by using the operator=(oslPipe), before you can use the stream- + functionality of the object. + */ + inline StreamPipe(); + + /** Creates pipe as wrapper around the underlying oslPipe. + @param Pipe + */ + inline StreamPipe(oslPipe Pipe); + + /** Copy constructor. + @param Pipe + */ + inline StreamPipe(const StreamPipe& Pipe); + + /** Creates a pipe. + @param strName + @param Options + */ + inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options = osl_Pipe_OPEN); + + /** Creates a pipe. + @param strName + @param Options + @param rSec + */ + inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security &rSec ); + + /** Constructs a Pipe reference without acquiring the handle + */ + inline StreamPipe( oslPipe pipe, __sal_NoAcquire noacquire ); + + /** Attaches the oslPipe to this object. If the object + already was attached to an oslPipe, the old one will + be closed and destroyed. + @param Pipe + */ + inline StreamPipe & SAL_CALL operator=(oslPipe Pipe); + + /** Assignment operator + */ + inline StreamPipe& SAL_CALL operator=(const Pipe& pipe); + + /** Tries to receives BytesToRead data from the connected pipe, + + @param pBuffer [out] Points to a buffer that will be filled with the received + data. + @param BytesToRead [in] The number of bytes to read. pBuffer must have at least + this size. + @return the number of received bytes. + */ + inline sal_Int32 SAL_CALL recv(void* pBuffer, sal_Int32 BytesToRead) const; + + /** Tries to sends BytesToSend data from the connected pipe. + + @param pBuffer [in] Points to a buffer that contains the send-data. + @param BytesToSend [in] The number of bytes to send. pBuffer must have at least + this size. + @return the number of transfered bytes. + */ + inline sal_Int32 SAL_CALL send(const void* pBuffer, sal_Int32 BytesToSend) const; + + /** Retrieves n bytes from the stream and copies them into pBuffer. + The method avoids incomplete reads due to packet boundaries. + @param pBuffer receives the read data. + @param n the number of bytes to read. pBuffer must be large enough + to hold the n bytes! + @return the number of read bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + inline sal_Int32 SAL_CALL read(void* pBuffer, sal_Int32 n) const; + + /** Writes n bytes from pBuffer to the stream. The method avoids + incomplete writes due to packet boundaries. + @param pBuffer contains the data to be written. + @param n the number of bytes to write. + @return the number of written bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + sal_Int32 SAL_CALL write(const void* pBuffer, sal_Int32 n) const; +}; + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/process.h b/include/osl/process.h new file mode 100644 index 000000000000..241f9a857552 --- /dev/null +++ b/include/osl/process.h @@ -0,0 +1,451 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef _OSL_PROCESS_H_ +#define _OSL_PROCESS_H_ + +#include "sal/config.h" + +#include "osl/file.h" +#include "osl/pipe.h" +#include "osl/security.h" +#include "osl/socket.h" +#include "osl/time.h" +#include "rtl/locale.h" +#include "rtl/textenc.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef sal_Int32 oslProcessOption; +#define osl_Process_WAIT 0x0001 /* wait for completion */ +#define osl_Process_SEARCHPATH 0x0002 /* search path for executable */ +#define osl_Process_DETACHED 0x0004 /* run detached */ +#define osl_Process_NORMAL 0x0000 /* run in normal window */ +#define osl_Process_HIDDEN 0x0010 /* run hidden */ +#define osl_Process_MINIMIZED 0x0020 /* run in minimized window */ +#define osl_Process_MAXIMIZED 0x0040 /* run in maximized window */ +#define osl_Process_FULLSCREEN 0x0080 /* run in fullscreen window */ + +typedef sal_Int32 oslProcessData; + +/* defines for osl_getProcessInfo , can be OR'ed */ +#define osl_Process_IDENTIFIER 0x0001 /* retrieves the process identifier */ +#define osl_Process_EXITCODE 0x0002 /* retrieves exit code of the process */ +#define osl_Process_CPUTIMES 0x0004 /* retrieves used cpu time */ +#define osl_Process_HEAPUSAGE 0x0008 /* retrieves the used size of heap */ + +typedef sal_uInt32 oslProcessIdentifier; +typedef sal_uInt32 oslProcessExitCode; + +typedef enum { + osl_Process_E_None, /* no error */ + osl_Process_E_NotFound, /* image not found */ + osl_Process_E_TimedOut, /* timout occurred */ + osl_Process_E_NoPermission, /* permission denied */ + osl_Process_E_Unknown, /* unknown error */ + osl_Process_E_InvalidError, /* unmapped error */ + osl_Process_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslProcessError; + +typedef enum { + osl_Process_TypeNone, /* no descriptor */ + osl_Process_TypeSocket, /* socket */ + osl_Process_TypeFile, /* file */ + osl_Process_TypePipe, /* pipe */ + osl_Process_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslDescriptorType; + +typedef sal_Int32 oslDescriptorFlag; +#define osl_Process_DFNONE 0x0000 +#define osl_Process_DFWAIT 0x0001 + +#ifdef SAL_W32 +# pragma pack(push, 8) +#endif + +typedef struct { + sal_uInt32 Size; + oslProcessData Fields; + oslProcessIdentifier Ident; + oslProcessExitCode Code; + TimeValue UserTime; + TimeValue SystemTime; + sal_uInt32 HeapUsage; +} oslProcessInfo; + +#if defined( SAL_W32) +# pragma pack(pop) +#endif + +/** Process handle + + @see osl_executeProcess + @see osl_terminateProcess + @see osl_freeProcessHandle + @see osl_getProcessInfo + @see osl_joinProcess +*/ +typedef void* oslProcess; + +/** Execute a process. + + Executes the program image provided in strImageName in a new process. + + @param ustrImageName + [in] The file URL of the executable to be started. + Can be NULL in this case the file URL of the executable must be the first element + in ustrArguments. + + @param ustrArguments + [in] An array of argument strings. Can be NULL if strImageName is not NULL. + If strImageName is NULL it is expected that the first element contains + the file URL of the executable to start. + + @param nArguments + [in] The number of arguments provided. If this number is 0 strArguments will be ignored. + + @param Options + [in] A combination of int-constants to describe the mode of execution. + + @param Security + [in] The user and his rights for which the process is started. May be NULL in which case + the process will be started in the context of the current user. + + @param ustrDirectory + [in] The file URL of the working directory of the new proces. If the specified directory + does not exist or is inaccessible the working directory of the newly created process + is undefined. If this parameter is NULL or the caller provides an empty string the + new process will have the same current working directory as the calling process. + + @param ustrEnvironments + [in] An array of strings describing environment variables that should be merged into the + environment of the new process. Each string has to be in the form "variable=value". + This parameter can be NULL in which case the new process gets the same environment + as the parent process. + + @param nEnvironmentVars + [in] The number of environment variables to set. + + @param pProcess + [out] Pointer to a oslProcess variable, wich receives the handle of the newly created process. + This parameter must not be NULL. + + @return + <dl> + <dt>osl_Process_E_None</dt> + <dd>on success</dd> + <dt>osl_Process_E_NotFound</dt> + <dd>if the specified executable could not be found</dd> + <dt>osl_Process_E_InvalidError</dt> + <dd>if invalid parameters will be detected</dd> + <dt>osl_Process_E_Unknown</dt> + <dd>if arbitrary other errors occur</dd> + </dl> + + @see oslProcessOption + @see osl_executeProcess_WithRedirectedIO + @see osl_freeProcessHandle + @see osl_loginUser +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_executeProcess( + rtl_uString* ustrImageName, + rtl_uString* ustrArguments[], + sal_uInt32 nArguments, + oslProcessOption Options, + oslSecurity Security, + rtl_uString* ustrDirectory, + rtl_uString* ustrEnvironments[], + sal_uInt32 nEnvironmentVars, + oslProcess* pProcess); + + +/** Execute a process and redirect child process standard IO. + + @param strImageName + [in] The file URL of the executable to be started. + Can be NULL in this case the file URL of the executable must be the first element + in ustrArguments. + + @param ustrArguments + [in] An array of argument strings. Can be NULL if strImageName is not NULL. + If strImageName is NULL it is expected that the first element contains + the file URL of the executable to start. + + @param nArguments + [in] The number of arguments provided. If this number is 0 strArguments will be ignored. + + @param Options + [in] A combination of int-constants to describe the mode of execution. + + @param Security + [in] The user and his rights for which the process is started. May be NULL in which case + the process will be started in the context of the current user. + + @param ustrDirectory + [in] The file URL of the working directory of the new proces. If the specified directory + does not exist or is inaccessible the working directory of the newly created process + is undefined. If this parameter is NULL or the caller provides an empty string the + new process will have the same current working directory as the calling process. + + @param ustrEnvironments + [in] An array of strings describing environment variables that should be merged into the + environment of the new process. Each string has to be in the form "variable=value". + This parameter can be NULL in which case the new process gets the same environment + as the parent process. + + @param nEnvironmentVars + [in] The number of environment variables to set. + + @param pProcess + [out] Pointer to a oslProcess variable, wich receives the handle of the newly created process. + This parameter must not be NULL. + + @param pChildInputWrite + [in] Pointer to a oslFileHandle variable that receives the handle which can be used to write + to the child process standard input device. The returned handle is not random accessible. + The handle has to be closed with osl_closeFile if no longer used. This parameter can be NULL. + + @param pChildOutputRead + [in] Pointer to a oslFileHandle variable that receives the handle which can be used to read from + the child process standard output device. The returned handle is not random accessible. + The Handle has to be closed with osl_closeFile if no longer used. This parameter can be NULL. + + @param pChildErrorRead + [in] Pointer to a oslFileHandle variable that receives the handle which can be used to read from + the child process standard error device. The returned handle is not random accessible. + The Handle has to be closed with osl_closeFile if no longer used. This parameter can be NULL. + + @return + <dl> + <dt>osl_Process_E_None</dt> + <dd>on success</dd> + <dt>osl_Process_E_NotFound</dt> + <dd>if the specified executable could not be found</dd> + <dt>osl_Process_E_InvalidError</dt> + <dd>if invalid parameters will be detected</dd> + <dt>osl_Process_E_Unknown</dt> + <dd>if arbitrary other errors occur</dd> + </dl> + + @see oslProcessOption + @see osl_executeProcess + @see osl_freeProcessHandle + @see osl_loginUser + @see osl_closeFile +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_executeProcess_WithRedirectedIO( + rtl_uString* strImageName, + rtl_uString* ustrArguments[], + sal_uInt32 nArguments, + oslProcessOption Options, + oslSecurity Security, + rtl_uString* ustrDirectory, + rtl_uString* ustrEnvironments[], + sal_uInt32 nEnvironmentVars, + oslProcess* pProcess, + oslFileHandle* pChildInputWrite, + oslFileHandle* pChildOutputRead, + oslFileHandle* pChildErrorRead); + +/** Terminate a process + @param Process [in] the handle of the process to be terminated + + @see osl_executeProcess + @see osl_getProcess + @see osl_joinProcess + */ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_terminateProcess( + oslProcess Process); + + +/** @deprecated + Retrieve the process handle of a process identifier + @param Ident [in] a process identifier + + @return the process handle on success, NULL in all other cases + */ +SAL_DLLPUBLIC oslProcess SAL_CALL osl_getProcess( + oslProcessIdentifier Ident); + + +/** Free the specified proces-handle. + @param Process [in] +*/ +SAL_DLLPUBLIC void SAL_CALL osl_freeProcessHandle( + oslProcess Process); + + +/** Wait for completation of the specified childprocess. + @param Process [in] + @return ols_Process_E_None + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_joinProcess( + oslProcess Process); + +/** Wait with a timeout for the completion of the specified child + process. + + @param Process [in] + A process identifier. + + @param pTimeout [in] + A timeout value or NULL for infinite waiting. + The unit of resolution is second. + + @return + osl_Process_E_None on success + osl_Process_E_TimedOut waiting for the child process timed out + osl_Process_E_Unknown an error occurred or the parameter are invalid + + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_joinProcessWithTimeout( + oslProcess Process, const TimeValue* pTimeout); + +/** Retrieves information about a Process + @param[in] Process the process handle of the process + @param[in] Fields the information which is to be retrieved + this can be one or more of + osl_Process_IDENTIFIER + osl_Process_EXITCODE + osl_Process_CPUTIMES + osl_Process_HEAPUSAGE + @param[out] pInfo a pointer to a vaid oslProcessInfo structure. + the Size field has to be initialized with the size + of the oslProcessInfo structure. + on success the Field member holds the (or'ed) + retrieved valid information fields. + @return osl_Process_E_None on success, osl_Process_E_Unknown on failure. + */ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getProcessInfo( + oslProcess Process, oslProcessData Fields, oslProcessInfo* pInfo); + +/** Get the filename of the executable. + @param strFile [out] the string that receives the executable file path. + @return osl_Process_E_None or does not return. + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getExecutableFile( + rtl_uString **strFile); + +/** @return the number of commandline arguments passed to the main-function of + this process + @see osl_getCommandArg +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getCommandArgCount(void); + +/** Get the nArg-th command-line argument passed to the main-function of this process. + @param nArg [in] The number of the argument to return. + @param strCommandArg [out] The string receives the nArg-th command-line argument. + @return osl_Process_E_None or does not return. + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getCommandArg( + sal_uInt32 nArg, rtl_uString **strCommandArg); + +/** Set the command-line arguments as passed to the main-function of this process. + + Depricated: This function is only for internal use. Passing the args from main will + only work for Unix, on Windows there's no effect, the full command line will automtically + be taken. This is due to Windows 9x/ME limitation that don't allow UTF-16 wmain to provide + a osl_setCommandArgsU( int argc, sal_Unicode **argv ); + + @param argc [in] The number of elements in the argv array. + @param argv [in] The array of command-line arguments. + @see osl_getExecutableFile + @see osl_getCommandArgCount + @see osl_getCommandArg +*/ +SAL_DLLPUBLIC void SAL_CALL osl_setCommandArgs (int argc, char **argv); + +/** Get the value of one enviroment variable. + @param strVar [in] denotes the name of the variable to get. + @param strValue [out] string that receives the value of environment variable. +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getEnvironment( + rtl_uString *strVar, rtl_uString **strValue); + +/** Set the value of one enviroment variable. + @param strVar [in] denotes the name of the variable to set. + @param strValue [in] string of the new value of environment variable. + + @since UDK 3.2.13 +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_setEnvironment( + rtl_uString *strVar, rtl_uString *strValue); + +/** Unsets the value of one enviroment variable. + @param strVar [in] denotes the name of the variable to unset. + + @since UDK 3.2.13 +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_clearEnvironment( + rtl_uString *strVar); + +/** Get the working directory of the current process as a file URL. + + The file URL is encoded as common for the OSL file API. + @param pustrWorkingDir [out] string that receives the working directory file URL. +*/ + +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getProcessWorkingDir( + rtl_uString **pustrWorkingDir ); + +/** Get the locale the process is currently running in. + + The unix implementation caches the value it returns, so if you have to change the locale + your are running in, you will have to use osl_setProcessLocale therefor. + + @param ppLocale [out] a pointer that receives the currently selected locale structure + @see osl_setProcessLocale +*/ + +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getProcessLocale( + rtl_Locale ** ppLocale ); + +/** Change the locale of the process. + + @param pLocale [in] a pointer to the locale to be set + @see osl_getProcessLocale +*/ + +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_setProcessLocale( + rtl_Locale * pLocale ); + + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_sendResourcePipe( + oslPipe Pipe, oslSocket Socket ); + +SAL_DLLPUBLIC oslSocket SAL_CALL osl_receiveResourcePipe( + oslPipe Pipe ); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_PROCESS_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/profile.h b/include/osl/profile.h new file mode 100644 index 000000000000..fcbf898c5754 --- /dev/null +++ b/include/osl/profile.h @@ -0,0 +1,145 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_PROFILE_H_ +#define _OSL_PROFILE_H_ + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef sal_uInt32 oslProfileOption; + +#define osl_Profile_DEFAULT 0x0000 +#define osl_Profile_SYSTEM 0x0001 /* use system depended functinality */ +#define osl_Profile_READLOCK 0x0002 /* lock file for reading */ +#define osl_Profile_WRITELOCK 0x0004 /* lock file for writing */ +#define osl_Profile_FLUSHWRITE 0x0010 /* writing only with flush */ + + +typedef void* oslProfile; + +/** Deprecated API. + Open or create a configuration profile. + @return 0 if the profile could not be created, otherwise a handle to the profile. + @deprecated +*/ +SAL_DLLPUBLIC oslProfile SAL_CALL osl_openProfile( + rtl_uString *strProfileName, oslProfileOption Options); + +/** Deprecated API. + Close the opened profile an flush all data to the disk. + @param Profile handle to a opened profile. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_closeProfile( + oslProfile Profile); + + +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_flushProfile( + oslProfile Profile); +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_readProfileString( + oslProfile Profile, + const sal_Char* pszSection, const sal_Char* pszEntry, + sal_Char* pszString, sal_uInt32 MaxLen, + const sal_Char* pszDefault); +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_readProfileBool( + oslProfile Profile, + const sal_Char* pszSection, const sal_Char* pszEntry, + sal_Bool Default); +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_readProfileIdent( + oslProfile Profile, + const sal_Char* pszSection, const sal_Char* pszEntry, + sal_uInt32 FirstId, const sal_Char* Strings[], + sal_uInt32 Default); + +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_writeProfileString( + oslProfile Profile, + const sal_Char* pszSection, const sal_Char* pszEntry, + const sal_Char* pszString); +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_writeProfileBool( + oslProfile Profile, + const sal_Char* pszSection, const sal_Char* pszEntry, + sal_Bool Value); +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_writeProfileIdent( + oslProfile Profile, + const sal_Char* pszSection, const sal_Char* pszEntry, + sal_uInt32 FirstId, const sal_Char* Strings[], + sal_uInt32 Value); + +/** Deprecated API. + Acquire the mutex, block if already acquired by another thread. + @return False if section or entry could not be found. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_removeProfileEntry( + oslProfile Profile, + const sal_Char *pszSection, const sal_Char *pszEntry); + +/** Deprecated API. + Get all entries belonging to the specified section. + @return Pointer to a array of pointers. + @deprecated +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getProfileSectionEntries( + oslProfile Profile, const sal_Char *pszSection, + sal_Char* pszBuffer, sal_uInt32 MaxLen); + +/** Deprecated API. + Get all section entries + @return Pointer to a array of pointers. + @deprecated +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getProfileSections( + oslProfile Profile, sal_Char* pszBuffer, sal_uInt32 MaxLen); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_PROFILE_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/profile.hxx b/include/osl/profile.hxx new file mode 100644 index 000000000000..452a37cbff39 --- /dev/null +++ b/include/osl/profile.hxx @@ -0,0 +1,196 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_PROFILE_HXX_ +#define _OSL_PROFILE_HXX_ + +#include "profile.h" +#include <rtl/ustring.hxx> +#include <string.h> +#include <list> + +namespace osl { + + typedef oslProfileOption ProfileOption; + + const int Profile_DEFAULT = osl_Profile_DEFAULT; + const int Profile_SYSTEM = osl_Profile_SYSTEM; /* use system depended functinality */ + const int Profile_READLOCK = osl_Profile_READLOCK; /* lock file for reading */ + const int Profile_WRITELOCK = osl_Profile_WRITELOCK; /* lock file for writing */ + + /** Deprecated API. + @deprecated + */ + class Profile { + oslProfile profile; + + public: + /** Open or create a configuration profile. + @return 0 if the profile could not be created, otherwise a handle to the profile. + */ + Profile(const rtl::OUString strProfileName, oslProfileOption Options = Profile_DEFAULT ) + { + profile = osl_openProfile(strProfileName.pData, Options); + if( ! profile ) + throw std::exception(); + } + + + /** Close the opened profile an flush all data to the disk. + */ + ~Profile() + { + osl_closeProfile(profile); + } + + + sal_Bool flush() + { + return osl_flushProfile(profile); + } + + rtl::OString readString( const rtl::OString& rSection, const rtl::OString& rEntry, + const rtl::OString& rDefault) + { + sal_Char aBuf[1024]; + return osl_readProfileString( profile, + rSection.getStr(), + rEntry.getStr(), + aBuf, + sizeof( aBuf ), + rDefault.getStr() ) ? rtl::OString( aBuf ) : rtl::OString(); + + } + + sal_Bool readBool( const rtl::OString& rSection, const rtl::OString& rEntry, sal_Bool bDefault ) + { + return osl_readProfileBool( profile, rSection.getStr(), rEntry.getStr(), bDefault ); + } + + sal_uInt32 readIdent(const rtl::OString& rSection, const rtl::OString& rEntry, + sal_uInt32 nFirstId, const std::list< rtl::OString >& rStrings, + sal_uInt32 nDefault) + { + int nItems = rStrings.size(); + const sal_Char** pStrings = new const sal_Char*[ nItems+1 ]; + std::list< rtl::OString >::const_iterator it = rStrings.begin(); + nItems = 0; + while( it != rStrings.end() ) + { + pStrings[ nItems++ ] = it->getStr(); + ++it; + } + pStrings[ nItems ] = NULL; + sal_uInt32 nRet = osl_readProfileIdent(profile, rSection.getStr(), rEntry.getStr(), nFirstId, pStrings, nDefault); + delete pStrings; + return nRet; + } + + sal_Bool writeString(const rtl::OString& rSection, const rtl::OString& rEntry, + const rtl::OString& rString) + { + return osl_writeProfileString(profile, rSection.getStr(), rEntry.getStr(), rString.getStr()); + } + + sal_Bool writeBool(const rtl::OString& rSection, const rtl::OString& rEntry, sal_Bool Value) + { + return osl_writeProfileBool(profile, rSection.getStr(), rEntry.getStr(), Value); + } + + sal_Bool writeIdent(const rtl::OString& rSection, const rtl::OString& rEntry, + sal_uInt32 nFirstId, const std::list< rtl::OString >& rStrings, + sal_uInt32 nValue) + { + int nItems = rStrings.size(); + const sal_Char** pStrings = new const sal_Char*[ nItems+1 ]; + std::list< rtl::OString >::const_iterator it = rStrings.begin(); + nItems = 0; + while( it != rStrings.end() ) + { + pStrings[ nItems++ ] = it->getStr(); + ++it; + } + pStrings[ nItems ] = NULL; + sal_Bool bRet = + osl_writeProfileIdent(profile, rSection.getStr(), rEntry.getStr(), nFirstId, pStrings, nValue ); + delete pStrings; + return bRet; + } + + /** Remove an entry from a section. + @param rSection Name of the section. + @param rEntry Name of the entry to remove. + @return False if section or entry could not be found. + */ + sal_Bool removeEntry(const rtl::OString& rSection, const rtl::OString& rEntry) + { + return osl_removeProfileEntry(profile, rSection.getStr(), rEntry.getStr()); + } + + /** Get all entries belonging to the specified section. + @param rSection Name of the section. + @return Pointer to a array of pointers. + */ + std::list< rtl::OString > getSectionEntries(const rtl::OString& rSection ) + { + std::list< rtl::OString > aEntries; + + // count buffer size necessary + int n = osl_getProfileSectionEntries( profile, rSection.getStr(), NULL, 0 ); + if( n > 1 ) + { + sal_Char* pBuf = new sal_Char[ n+1 ]; + osl_getProfileSectionEntries( profile, rSection.getStr(), pBuf, n+1 ); + int nLen; + for( n = 0; ( nLen = strlen( pBuf+n ) ); n += nLen+1 ) + aEntries.push_back( rtl::OString( pBuf+n ) ); + delete pBuf; + } + + return aEntries; + } + + /** Get all section entries + @return Pointer to a array of pointers. + */ + std::list< rtl::OString > getSections() + { + std::list< rtl::OString > aSections; + + // count buffer size necessary + int n = osl_getProfileSections( profile, NULL, 0 ); + if( n > 1 ) + { + sal_Char* pBuf = new sal_Char[ n+1 ]; + osl_getProfileSections( profile, pBuf, n+1 ); + int nLen; + for( n = 0; ( nLen = strlen( pBuf+n ) ); n += nLen+1 ) + aSections.push_back( rtl::OString( pBuf+n ) ); + delete pBuf; + } + + return aSections; + } + }; +} + +#endif /* _OSL_PROFILE_HXX_ */ + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/security.h b/include/osl/security.h new file mode 100644 index 000000000000..b24625761731 --- /dev/null +++ b/include/osl/security.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_SECURITY_H_ +#define _OSL_SECURITY_H_ + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + osl_Security_E_None, + osl_Security_E_UserUnknown, + osl_Security_E_WrongPassword, + osl_Security_E_Unknown, + osl_Security_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSecurityError; + +/** Process handle + @see osl_loginUser + @see osl_freeSecurityHandle + @see osl_executeProcess +*/ +typedef void* oslSecurity; + +/** Create a security handle for the current user. + @return a security handle or NULL on failure. + @see osl_freeSecurityHandle + @see osl_executeProcess + @see osl_executeApplication +*/ +SAL_DLLPUBLIC oslSecurity SAL_CALL osl_getCurrentSecurity(void); + +/** Deprecated API + Create a security handle for the denoted user. + Try to log in the user on the local system. + @param[in] strUserName denotes the name of the user to logg in. + @param[in] strPasswd the password for this user. + @param[out] pSecurity returns the security handle if user could be logged in. + @return osl_Security_E_None if user could be logged in, otherwise an error-code. + @see osl_freeSecurityHandle + @see osl_executeProcess + @see osl_executeApplication +*/ +SAL_DLLPUBLIC oslSecurityError SAL_CALL osl_loginUser( + rtl_uString *strUserName, + rtl_uString *strPasswd, + oslSecurity *pSecurity + ); + +/** Create a security handle for the denoted user. + Try to log in the user on the denoted file server. On success the homedir will be + the maped drive on this server. + @param[in] strUserName denotes the name of the user to logg in. + @param[in] strPasswd the password for this user. + @param[in] strFileServer denotes the file server on wich the user is logged in. + @param[out] pSecurity returns the security handle if user could be logged in. + @return osl_Security_E_None if user could be logged in, otherwise an error-code. + @see osl_freeSecurityHandle + @see osl_executeProcess + @see osl_executeApplication +*/ +SAL_DLLPUBLIC oslSecurityError SAL_CALL osl_loginUserOnFileServer( + rtl_uString *strUserName, + rtl_uString *strPasswd, + rtl_uString *strFileServer, + oslSecurity *pSecurity + ); + +/** Query if the user who is denotes by this security has administrator rigths. + @param[in] Security the security handle for th user. + @return True, if the user has adminsitrator rights, otherwise false. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isAdministrator( + oslSecurity Security); + +/** Free the security handle, created by osl_loginUser or osl_getCurrentSecurity. + @param[in] Security the security handle. + @see osl_loginUser +*/ +SAL_DLLPUBLIC void SAL_CALL osl_freeSecurityHandle( + oslSecurity Security); + +/** Get the login ident for the user of this security handle. + @param[in] Security the security handle. + @param[out] strIdent the string that receives the ident on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getUserIdent( + oslSecurity Security, rtl_uString **strIdent); + +/** Get the login name for the user of this security handle. + @param[in] Security the security handle. + @param[out] strName the string that receives the user name on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getUserName( + oslSecurity Security, rtl_uString **strName); + +/** Get the home directory of the user of this security handle. + @param[in] Security the security handle. + @param[out] strDirectory the string that receives the directory path on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getHomeDir( + oslSecurity Security, rtl_uString **strDirectory); + +/** Get the directory for configuration data of the user of this security handle. + @param[in] Security the security handle. + @param[out] strDirectory the string that receives the directory path on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getConfigDir( + oslSecurity Security, rtl_uString **strDirectory); + + +/** Load Profile of the User + Implemented just for Windows + @param[in] Security previously fetch Security of the User + @return True if the Profile could successfully loaded, False otherwise. +*/ + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_loadUserProfile( + oslSecurity Security); + + +/** Unload a User Profile + Implemented just for Windows + @param[in] Security previously fetch Security of the User + @return nothing is returned! +*/ + +SAL_DLLPUBLIC void SAL_CALL osl_unloadUserProfile( + oslSecurity Security); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_SECURITY_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/security.hxx b/include/osl/security.hxx new file mode 100644 index 000000000000..941b2c5980a8 --- /dev/null +++ b/include/osl/security.hxx @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_SECURITY_HXX_ +#define _OSL_SECURITY_HXX_ + +#include <rtl/ustring.hxx> + +#ifndef _OSL_SECURITY_DECL_HXX +# include <osl/security_decl.hxx> +#endif + +namespace osl +{ + +inline Security::Security() +{ + m_handle = osl_getCurrentSecurity(); +} + +inline Security::~Security() +{ + osl_freeSecurityHandle(m_handle); +} + +inline sal_Bool Security::logonUser(const rtl::OUString& strName, + const rtl::OUString& strPasswd) +{ + osl_freeSecurityHandle(m_handle); + + m_handle = 0; + + return (osl_loginUser( strName.pData, strPasswd.pData, &m_handle) + == osl_Security_E_None); +} + +inline sal_Bool Security::logonUser( const rtl::OUString& strName, + const rtl::OUString& strPasswd, + const rtl::OUString& strFileServer ) +{ + osl_freeSecurityHandle(m_handle); + + m_handle = NULL; + + return (osl_loginUserOnFileServer(strName.pData, strPasswd.pData, strFileServer.pData, &m_handle) + == osl_Security_E_None); +} + +inline sal_Bool Security::getUserIdent( rtl::OUString& strIdent) const +{ + return osl_getUserIdent( m_handle, &strIdent.pData ); +} + + +inline sal_Bool Security::getUserName( rtl::OUString& strName ) const +{ + return osl_getUserName( m_handle, &strName.pData ); +} + + +inline sal_Bool Security::getHomeDir( rtl::OUString& strDirectory) const +{ + return osl_getHomeDir(m_handle, &strDirectory.pData ); +} + + +inline sal_Bool Security::getConfigDir( rtl::OUString& strDirectory ) const +{ + return osl_getConfigDir( m_handle, &strDirectory.pData ); +} + +inline sal_Bool Security::isAdministrator() const +{ + return osl_isAdministrator(m_handle); +} + +inline oslSecurity Security::getHandle() const +{ + return m_handle; +} + + +} + +#endif // _OSL_SECURITY_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/security_decl.hxx b/include/osl/security_decl.hxx new file mode 100644 index 000000000000..ba2f4195d769 --- /dev/null +++ b/include/osl/security_decl.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_SECURITY_DECL_HXX_ +#define _OSL_SECURITY_DECL_HXX_ + +#include <rtl/ustring.hxx> +# include <osl/security.h> + +namespace osl +{ + +/** capsulate security information for one user. + A object of this class is used to execute a process with the rights an + security options of a scecified user. + @see Process::executeProcess +*/ +class Security +{ +protected: + oslSecurity m_handle; + +public: + /// constructor + inline Security(); + /// destructor + inline ~Security(); + /** get the security information for one user. + The underlying operating system is asked for this information. + @param[in] strName denotes the name of the user + @param[in] strPasswd denotes the password of this user + @return True, if the specified user is known by the underlying operating system, + otherwise False + */ + inline sal_Bool SAL_CALL logonUser(const rtl::OUString& strName, + const rtl::OUString& strPasswd); + /** get the security information for one user. + + @verbatim + This method will try to login the user at the denoted file server. + If a network resource named \\server\username exists and this resource + could be connected by this user, the methos will return true and getHomeDir + will return \\server\username. + @endverbatim + @param[in] strName denotes the name of the user + @param[in] strPasswd denotes the password of this user + @param[in] strFileServer denotes the file server to login to + @return True, if the specified user is known by file server and the + could be connected, otherwise False + */ + inline sal_Bool SAL_CALL logonUser(const rtl::OUString & strName, + const rtl::OUString & strPasswd, + const rtl::OUString & strFileServer); + + /** get the ident of the logged in user. + @param[out] strIdent is the OUString which returns the name + @return True, if any user is successfully logged in, otherwise False + */ + inline sal_Bool SAL_CALL getUserIdent( rtl::OUString& strIdent) const; + + /** get the name of the logged in user. + @param[out] strName is the OUString which returns the name + @return True, if any user is successfully logged in, otherwise False + */ + inline sal_Bool SAL_CALL getUserName( rtl::OUString& strName) const; + + /** get the home directory of the logged in user. + @param[out] strDirectory is the OUString which returns the directory name + @return True, if any user is successfully logged in, otherwise False + */ + inline sal_Bool SAL_CALL getHomeDir( rtl::OUString& strDirectory) const; + + /** get the directory for configuration data of the logged in user. + @param[out] strDirectory is the OUString which returns the directory name + @return True, if any user is successfully logged in, otherwise False + */ + inline sal_Bool SAL_CALL getConfigDir( rtl::OUString & strDirectory) const; + + /** Query if the user who is logged inhas administrator rigths. + @return True, if the user has administrator rights, otherwise false. + */ + inline sal_Bool SAL_CALL isAdministrator() const; + + /** Returns the underlying oslSecurity handle + */ + inline oslSecurity getHandle() const; + +}; + +} + +#endif // _OSL_SECURITY_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/signal.h b/include/osl/signal.h new file mode 100644 index 000000000000..ca113308cf92 --- /dev/null +++ b/include/osl/signal.h @@ -0,0 +1,112 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_SIGNAL_H_ +#define _OSL_SIGNAL_H_ + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define OSL_SIGNAL_USER_RESERVED 0 + +#define OSL_SIGNAL_USER_RESOURCEFAILURE (OSL_SIGNAL_USER_RESERVED - 1) +#define OSL_SIGNAL_USER_X11SUBSYSTEMERROR (OSL_SIGNAL_USER_RESERVED - 2) +#define OSL_SIGNAL_USER_RVPCONNECTIONERROR (OSL_SIGNAL_USER_RESERVED - 3) + +typedef void* oslSignalHandler; + +typedef enum +{ + osl_Signal_System, + osl_Signal_Terminate, + osl_Signal_AccessViolation, + osl_Signal_IntegerDivideByZero, + osl_Signal_FloatDivideByZero, + osl_Signal_DebugBreak, + osl_Signal_User, + osl_Signal_Alarm, + osl_Signal_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSignal; + +typedef enum +{ + osl_Signal_ActCallNextHdl, + osl_Signal_ActIgnore, + osl_Signal_ActAbortApp, + osl_Signal_ActKillApp, + osl_Signal_Act_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSignalAction; + +#ifdef SAL_W32 +# pragma pack(push, 8) +#endif + +typedef struct +{ + oslSignal Signal; + sal_Int32 UserSignal; + void* UserData; +} oslSignalInfo; + +#if defined( SAL_W32) +# pragma pack(pop) +#endif + +/** the function-ptr. representing the signal handler-function. +*/ +typedef oslSignalAction (SAL_CALL *oslSignalHandlerFunction)(void* pData, oslSignalInfo* pInfo); + +SAL_DLLPUBLIC oslSignalHandler SAL_CALL osl_addSignalHandler( + oslSignalHandlerFunction Handler, void* pData); + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_removeSignalHandler( + oslSignalHandler hHandler); + +SAL_DLLPUBLIC oslSignalAction SAL_CALL osl_raiseSignal( + sal_Int32 UserSignal, void* UserData); + +/** Enables or disables error reporting + + On default error reporting is enabled after process startup. + + @param bEnable [in] + Enables or disables error reporting. + + @return + sal_True if previous state of error reporting was enabled<br> + sal_False if previous state of error reporting was disbaled<br> +*/ + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setErrorReporting( + sal_Bool bEnable ); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_SIGNAL_H_ */ + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/socket.h b/include/osl/socket.h new file mode 100644 index 000000000000..8ccb2c740f53 --- /dev/null +++ b/include/osl/socket.h @@ -0,0 +1,920 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_SOCKET_H_ +#define _OSL_SOCKET_H_ + +#include <rtl/ustring.h> +#include <rtl/byteseq.h> + +#include <osl/time.h> +#include <rtl/tencinfo.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* error returns */ +#define OSL_INADDR_NONE 0xffffffff +#define OSL_INVALID_PORT (-1) +#define OSL_INVALID_IPX_SOCKET_NO 0xffffffff + +/** + Opaque datatype SocketAddr. +*/ +typedef struct oslSocketAddrImpl * oslSocketAddr; + + +/** + Represents the address-family of a socket +*/ +typedef enum { + osl_Socket_FamilyInet, /* IP */ + osl_Socket_FamilyIpx, /* Novell IPX/SPX */ + osl_Socket_FamilyInvalid, /* always last entry in enum! */ + osl_Socket_Family_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslAddrFamily; + +/** + represent a specific protocol within a address-family +*/ +typedef enum { + osl_Socket_ProtocolIp, /* for all af_inet */ + osl_Socket_ProtocolIpx, /* af_ipx datagram sockets (IPX) */ + osl_Socket_ProtocolSpx, /* af_ipx seqpacket or stream for SPX */ + osl_Socket_ProtocolSpxII, /* af_ipx seqpacket or stream for SPX II */ + osl_Socket_ProtocolInvalid, + osl_Socket_Protocol_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslProtocol; + + +/** + Represents the type of a socket +*/ +typedef enum { + osl_Socket_TypeStream, + osl_Socket_TypeDgram, + osl_Socket_TypeRaw, + osl_Socket_TypeRdm, + osl_Socket_TypeSeqPacket, + osl_Socket_TypeInvalid, /* always last entry in enum! */ + osl_Socket_Type_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketType; + + +/** + Represents socket-options +*/ +typedef enum { + osl_Socket_OptionDebug, + osl_Socket_OptionAcceptConn, + osl_Socket_OptionReuseAddr, + osl_Socket_OptionKeepAlive, + osl_Socket_OptionDontRoute, + osl_Socket_OptionBroadcast, + osl_Socket_OptionUseLoopback, + osl_Socket_OptionLinger, + osl_Socket_OptionOOBinLine, + osl_Socket_OptionSndBuf, + osl_Socket_OptionRcvBuf, + osl_Socket_OptionSndLowat, + osl_Socket_OptionRcvLowat, + osl_Socket_OptionSndTimeo, + osl_Socket_OptionRcvTimeo, + osl_Socket_OptionError, + osl_Socket_OptionType, + osl_Socket_OptionTcpNoDelay, + osl_Socket_OptionInvalid, /* always last entry in enum! */ + osl_Socket_Option_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketOption; + +/** + Represents the different socket-option levels +*/ +typedef enum { + osl_Socket_LevelSocket, + osl_Socket_LevelTcp, + osl_Socket_LevelInvalid, /* always last entry in enum! */ + osl_Socket_Level_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketOptionLevel; + + +/** + Represents flags to be used with send/recv-calls. +*/ +typedef enum { + osl_Socket_MsgNormal, + osl_Socket_MsgOOB, + osl_Socket_MsgPeek, + osl_Socket_MsgDontRoute, + osl_Socket_MsgMaxIOVLen, + osl_Socket_MsgInvalid, /* always last entry in enum! */ + osl_Socket_Msg_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketMsgFlag; + +/** + Used by shutdown to denote which end of the socket to "close". +*/ +typedef enum { + osl_Socket_DirRead, + osl_Socket_DirWrite, + osl_Socket_DirReadWrite, + osl_Socket_DirInvalid, /* always last entry in enum! */ + osl_Socket_Dir_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketDirection; + +/** Describes the various error socket error conditions, which may + occur */ +typedef enum { + osl_Socket_E_None, /* no error */ + osl_Socket_E_NotSocket, /* Socket operation on non-socket */ + osl_Socket_E_DestAddrReq, /* Destination address required */ + osl_Socket_E_MsgSize, /* Message too long */ + osl_Socket_E_Prototype, /* Protocol wrong type for socket */ + osl_Socket_E_NoProtocol, /* Protocol not available */ + osl_Socket_E_ProtocolNoSupport, /* Protocol not supported */ + osl_Socket_E_TypeNoSupport, /* Socket type not supported */ + osl_Socket_E_OpNotSupport, /* Operation not supported on socket */ + osl_Socket_E_PfNoSupport, /* Protocol family not supported */ + osl_Socket_E_AfNoSupport, /* Address family not supported by */ + /* protocol family */ + osl_Socket_E_AddrInUse, /* Address already in use */ + osl_Socket_E_AddrNotAvail, /* Can't assign requested address */ + osl_Socket_E_NetDown, /* Network is down */ + osl_Socket_E_NetUnreachable, /* Network is unreachable */ + osl_Socket_E_NetReset, /* Network dropped connection because */ + /* of reset */ + osl_Socket_E_ConnAborted, /* Software caused connection abort */ + osl_Socket_E_ConnReset, /* Connection reset by peer */ + osl_Socket_E_NoBufferSpace, /* No buffer space available */ + osl_Socket_E_IsConnected, /* Socket is already connected */ + osl_Socket_E_NotConnected, /* Socket is not connected */ + osl_Socket_E_Shutdown, /* Can't send after socket shutdown */ + osl_Socket_E_TooManyRefs, /* Too many references: can't splice */ + osl_Socket_E_TimedOut, /* Connection timed out */ + osl_Socket_E_ConnRefused, /* Connection refused */ + osl_Socket_E_HostDown, /* Host is down */ + osl_Socket_E_HostUnreachable, /* No route to host */ + osl_Socket_E_WouldBlock, /* call would block on non-blocking socket */ + osl_Socket_E_Already, /* operation already in progress */ + osl_Socket_E_InProgress, /* operation now in progress */ + osl_Socket_E_InvalidError, /* unmapped error: always last entry in enum! */ + osl_Socket_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketError; + +/** Common return codes of socket related functions. + */ +typedef enum { + osl_Socket_Ok, /* successful completion */ + osl_Socket_Error, /* error occurred, check osl_getLastSocketError() for details */ + osl_Socket_TimedOut, /* blocking operation timed out */ + osl_Socket_Interrupted, /* blocking operation was interrupted */ + osl_Socket_InProgress, /* nonblocking operation is in progress */ + osl_Socket_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketResult; + +typedef sal_uInt8 oslSocketIpxNetNumber[4]; +typedef sal_uInt8 oslSocketIpxNodeNumber[6]; + +/**@} end section types +*/ + +/**@{ begin section oslSocketAddr +*/ + +/** Creates a socket-address for the given family. + @param Family If family == osl_Socket_FamilyInet the address is + set to INADDR_ANY port 0. + @return 0 if address could not be created. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_createEmptySocketAddr( + oslAddrFamily Family); + + +/** Creates a new SocketAddress and fills it from Addr. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_copySocketAddr( + oslSocketAddr Addr); + +/** Compares the values of two SocketAddresses. + @return <code>sal_True</code> if both addresses denote the same socket address, + <code>sal_False</code> otherwise. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isEqualSocketAddr( + oslSocketAddr Addr1, oslSocketAddr Addr2); + +/** Uses the systems name-service interface to find an address for strHostname. + @param[in] strHostname The name for which you search for an address. + @return The desired address if one could be found, otherwise 0. + Don't forget to destroy the address if you don't need it any longer. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_resolveHostname( + rtl_uString *strHostname); + +/** Create an internet address usable for sending broadcast datagrams. + To limit the broadcast to your subnet, pass your hosts IP address + in dotted decimal notation as first argument. + @see osl_sendToSocket() + @see oslSocketAddr + @param[in] strDottedAddr dotted decimal internet address, may be 0. + @param[in] Port port number in host byte order. + @return 0 if address could not be created. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_createInetBroadcastAddr ( + rtl_uString *strDottedAddr, sal_Int32 Port); + + +/** Create an internet-address, consisting of hostaddress and port. + We interpret strDottedAddr as a dotted-decimal inet-addr + (e.g. "141.99.128.50"). + @param strDottedAddr [in] String with dotted address. + @param Port [in] portnumber in host byte order. + @return 0 if address could not be created. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_createInetSocketAddr ( + rtl_uString *strDottedAddr, sal_Int32 Port); + + +/** Frees all resources allocated by Addr. The handle Addr must not + be used after the call anymore. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroySocketAddr( + oslSocketAddr Addr); + +/** Looks up the port-number designated to the specified service/protocol-pair. + (e.g. "ftp" "tcp"). + @return OSL_INVALID_PORT if no appropriate entry was found, otherwise the port-number. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_getServicePort( + rtl_uString *strServicename, rtl_uString *strProtocol); + + + +/** Retrieves the address-family from the Addr. + @return the family of the socket-address. + In case of an unknown family you get <code>osl_Socket_FamilyInvalid</code>. +*/ +SAL_DLLPUBLIC oslAddrFamily SAL_CALL osl_getFamilyOfSocketAddr( + oslSocketAddr Addr); + + +/** Retrieves the internet port-number of Addr. + @return the port-number of the address in host-byte order. If Addr + is not an address of type <code>osl_Socket_FamilyInet</code>, it returns <code>OSL_INVALID_PORT</code> +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_getInetPortOfSocketAddr( + oslSocketAddr Addr); + + +/** Sets the Port of Addr. + @param[in] Addr the SocketAddr to perfom the operation on. + @param[in] Port is expected in host byte-order. + @return <code>sal_False</code> if Addr is not an inet-addr. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setInetPortOfSocketAddr( + oslSocketAddr Addr, sal_Int32 Port); + + +/** Returns the hostname represented by Addr. + @param[in] Addr The socket address from which to extract the hostname. + @param[out] strHostname The hostname represented by the address. If + there is no hostname to be found, it returns 0. +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getHostnameOfSocketAddr( + oslSocketAddr Addr, rtl_uString **strHostname); + + +/** Gets the address in dotted decimal format. + @param[in] Addr The socket address from which to extract the dotted decimal address. + @param[out] strDottedInetAddr Contains the dotted decimal address + (e.g. 141.99.20.34) represented by the address. + If the address is invalid or not of type <code>osl_Socket_FamilyInet</code>, + it returns 0. + @return <code>osl_Socket_Ok</code> or <code>osl_Socket_Error</code> +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getDottedInetAddrOfSocketAddr( + oslSocketAddr Addr, rtl_uString **strDottedInetAddr); + +/** Sets the addr field in the struct sockaddr with pByteSeq. pByteSeq must be in network byte order. + */ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_setAddrOfSocketAddr( + oslSocketAddr Addr, sal_Sequence *pByteSeq ); + +/** Returns the addr field in the struct sockaddr. + @param[in] Addr The socket address from which to extract the ipaddress. + @param[out] ppByteSeq After the call, *ppByteSeq contains the ipaddress + in network byteorder. *ppByteSeq may be 0 in case of an invalid socket handle. + @return <code>osl_Socket_Ok</code> or <code>osl_Socket_Error</code> + */ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getAddrOfSocketAddr( + oslSocketAddr Addr, sal_Sequence **ppByteSeq ); + +/* + Opaque datatype HostAddr. +*/ +typedef struct oslHostAddrImpl * oslHostAddr; + + +/** Create an oslHostAddr from given hostname and socket address. + @param[in] strHostname The hostname to be stored. + @param[in] Addr The socket address to be stored. + @return The created address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_createHostAddr( + rtl_uString *strHostname, const oslSocketAddr Addr); + + +/** Create an oslHostAddr by resolving the given strHostname. + Successful name resolution should result in the fully qualified + domain name (FQDN) and it's address as hostname and socket address + members of the resulting oslHostAddr. + @param[in] strHostname The hostname to be resolved. + @return The resulting address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_createHostAddrByName(rtl_uString *strHostname); + + +/** Create an oslHostAddr by reverse resolution of the given Addr. + Successful name resolution should result in the fully qualified + domain name (FQDN) and it's address as hostname and socket address + members of the resulting oslHostAddr. + @param[in] Addr The socket address to be reverse resolved. + @return The resulting address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_createHostAddrByAddr(const oslSocketAddr Addr); + + +/** Create a copy of the given Addr. + @return The copied address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_copyHostAddr(const oslHostAddr Addr); + + +/** Frees all resources allocated by Addr. The handle Addr must not + be used after the call anymore. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyHostAddr(oslHostAddr Addr); + + +/** Get the hostname member of Addr. + @return The hostname or 0 upon failure. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_getHostnameOfHostAddr(const oslHostAddr Addr, rtl_uString **strHostname); + + +/** Get the socket address member of Addr. + @return The socket address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_getSocketAddrOfHostAddr(const oslHostAddr Addr); + +/** Retrieve this machines hostname. + May not always be a fully qualified domain name (FQDN). + @param strLocalHostname out-parameter. The string that receives the local host name. + @return <code>sal_True</code> upon success, <code>sal_False</code> otherwise. +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getLocalHostname(rtl_uString **strLocalHostname); + + +/**@} end section oslHostAddr +*/ + +/**@{ begin section oslSocket +*/ + + +/*-***************************************************************************/ +/* oslSocket */ +/*-***************************************************************************/ + +typedef struct oslSocketImpl * oslSocket; + +/** increases the refcount of the socket handle by one + */ +SAL_DLLPUBLIC void SAL_CALL osl_acquireSocket( oslSocket Socket ); + +/** decreases the refcount of the socket handle by one. + + If the refcount drops to zero, the underlying socket handle + is destroyed and becomes invalid. + */ +SAL_DLLPUBLIC void SAL_CALL osl_releaseSocket( oslSocket Socket ); + +/** Create a socket of the specified Family and Type. The semantic of + the Protocol parameter depends on the given family and type. + @return 0 if socket could not be created, otherwise you get a handle + to the allocated socket-datastructure. +*/ +SAL_DLLPUBLIC oslSocket SAL_CALL osl_createSocket( + oslAddrFamily Family, + oslSocketType Type, + oslProtocol Protocol); + +/** Retrieves the Address of the local end of the socket. + Note that a socket must be bound or connected before + a vaild address can be returned. + @return 0 if socket-address could not be created, otherwise you get + the created Socket-Address. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_getLocalAddrOfSocket(oslSocket Socket); + +/** Retrieves the Address of the remote end of the socket. + Note that a socket must be connected before + a vaild address can be returned. + @return 0 if socket-address could not be created, otherwise you get + the created Socket-Address. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_getPeerAddrOfSocket(oslSocket Socket); + +/** Binds the given address to the socket. + @param[in] Socket + @param[in] Addr + @return <code>sal_False</code> if the bind failed, <code> sal_True</code> if successful. + @see osl_getLastSocketError() +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_bindAddrToSocket( + oslSocket Socket, + oslSocketAddr Addr); + +/** Connects the socket to the given address. + + @param[in] Socket a bound socket. + @param[in] Addr the peer address. + @param pTimeout Timeout value or NULL for blocking. + + @return <code>osl_Socket_Ok</code> on successful connection, + <code>osl_Socket_TimedOut</code> if operation timed out, + <code>osl_Socket_Interrupted</code> if operation was interrupted + <code>osl_Socket_Error</code> if the connection failed. +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_connectSocketTo( + oslSocket Socket, + oslSocketAddr Addr, + const TimeValue* pTimeout); + + +/** Prepares the socket to act as an acceptor of incoming connections. + You should call "listen" before you use "accept". + @param[in] Socket The socket to listen on. + @param[in] MaxPendingConnections denotes the length of the queue of + pending connections for this socket. If MaxPendingConnections is + -1, the systems default value will be used (Usually 5). + @return <code>sal_False</code> if the listen failed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_listenOnSocket( + oslSocket Socket, + sal_Int32 MaxPendingConnections); + + +/** Waits for an ingoing connection on the socket. + This call blocks if there is no incoming connection present. + @param[in] Socket The socket to accept the connection on. + @param[in] pAddr if pAddr is != 0, the peers address is returned. + @return 0 if the accept-call failed, otherwise you get a socket + representing the new connection. +*/ +SAL_DLLPUBLIC oslSocket SAL_CALL osl_acceptConnectionOnSocket + (oslSocket Socket, + oslSocketAddr* pAddr); + +/** Tries to receive BytesToRead data from the connected socket, + if no error occurs. Note that incomplete recvs due to + packet boundaries may occur. + + @param[in] Socket A connected socket to be used to listen on. + @param[out] pBuffer Points to a buffer that will be filled with the received + data. + @param[in] BytesToRead The number of bytes to read. pBuffer must have at least + this size. + @param[in] Flag Modifier for the call. Valid values are: + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of received bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_receiveSocket( + oslSocket Socket, + void* pBuffer, + sal_uInt32 BytesToRead, + oslSocketMsgFlag Flag); + +/** Tries to receives BufferSize data from the (usually unconnected) + (datagram-)socket, if no error occurs. + + @param[in] Socket A bound socket to be used to listen for a datagram. + @param[out] SenderAddr A pointer to a created oslSocketAddr handle + or to a null handle. After the call, it will contain the constructed + oslSocketAddr of the datagrams sender. If pSenderAddr itself is 0, + it is ignored. + @param[out] pBuffer Points to a buffer that will be filled with the received + datagram. + @param[in] BufferSize The size of pBuffer. + @param[in] Flag Modifier for the call. Valid values are: + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of received bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_receiveFromSocket( + oslSocket Socket, + oslSocketAddr SenderAddr, + void* pBuffer, + sal_uInt32 BufferSize, + oslSocketMsgFlag Flag); + +/** Tries to send BytesToSend data from the connected socket, + if no error occurs. + + @param[in] Socket A connected socket. + @param[in] pBuffer Points to a buffer that contains the send-data. + @param[in] BytesToSend The number of bytes to send. pBuffer must have at least + this size. + @param[in] Flag Modifier for the call. Valid values are: + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of transfered bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_sendSocket( + oslSocket Socket, + const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag Flag); + +/** Tries to send one datagram with BytesToSend data to the given ReceiverAddr + via the (implicitly unconnected) datagram-socket. + Since there is only sent one packet, the function sends the data always complete + even with incomplete packet boundaries. + + @param[in] Socket A bound or unbound socket. Socket will be bound + after a successful call. + + @param[in] ReceiverAddr An initialized oslSocketAddress that contains + the destination address for this send. + + @param[in] pBuffer Points to a buffer that contains the send-data. + @param[in] BytesToSend The number of bytes to send. pBuffer must have at least + this size. + @param Flag [in] Modifier for the call. Valid values are: + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of transfered bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_sendToSocket( + oslSocket Socket, + oslSocketAddr ReceiverAddr, + const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag Flag); + +/** Checks if read operations will block. + + You can specify a timeout-value in seconds/microseconds that denotes + how long the operation will block if the Socket is not ready. + + @return <code>sal_True</code> if read operations (recv, recvFrom, accept) on the Socket + will NOT block; <code>sal_False</code> if it would block or if an error occurred. + + @param Socket the Socket to perfom the operation on. + @param pTimeout if NULL, the operation will block without a timeout. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isReceiveReady( + oslSocket Socket, const TimeValue* pTimeout); + +/** Checks if send operations will block. + You can specify a timeout-value in seconds/microseconds that denotes + how long the operation will block if the Socket is not ready. + @return <code>sal_True</code> if send operations (send, sendTo) on the Socket + will NOT block; <code>sal_False</code> if it would block or if an error occurred. + + @param Socket the Socket to perfom the operation on. + @param pTimeout if NULL, the operation will block without a timeout. Otherwise + the time define by timeout value. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isSendReady( + oslSocket Socket, const TimeValue* pTimeout); + +/** Checks if a request for out-of-band data will block. + You can specify a timeout-value in seconds/microseconds that denotes + how long the operation will block if the Socket has no pending OOB data. + @return <code>sal_True</code> if OOB-request operations (recv with appropriate flags) + on the Socket will NOT block; <code>sal_False</code> if it would block or if an error occurred. + + @param Socket the Socket to perfom the operation on. + @param pTimeout if NULL, the operation will block without a timeout. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isExceptionPending( + oslSocket Socket, const TimeValue* pTimeout); + +/** Shuts down communication on a connected socket. + @param[in] Socket the Socket to perfom the operation on. + @param[in] Direction denotes which end of the socket + should be closed: + <ul> + <li> <code>osl_Socket_DirRead</code> closes read operations. + <li> <code>osl_Socket_DirReadWrite</code> closes write operations. + <li> <code>osl_Socket_DirWrite</code> closes read and write operations. + </ul> + @return <code>sal_True</code> if the socket could be closed down. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_shutdownSocket(oslSocket Socket, + oslSocketDirection Direction); + +/** Retrieves attributes associated with the socket. + @param Socket is the socket to query. + + @param Level selects the level for which an option should be queried. + Valid values are: + <ul> + <li> osl_sol_socket: Socket Level + <li> osl_sol_tcp: Level of Transmission Control Protocol + </ul> + + @param Option denotes the option to query. + Valid values (depending on the Level) are: + <ul> + <li> <code>osl_Socket_Option_Debug</code><br> + (sal_Bool) Socket debug flag 1 = enabled, 0 = disabled. + + <li> <code>osl_Socket_OptionAcceptConn</code><br> + <li> <code>osl_Socket_OptionReuseAddr</code><br> + (sal_Bool) Allows the socket to be bound to an address that is + already in use. + 1 = multiple bound allowed, 0 = no multiple bounds allowed + + <li><code>osl_Socket_OptionKeepAlive</code><br> + (sal_Bool) Keepalive packets are sent by the underlying socket. + 1 = enabled, 0 = disabled + + <li><code>osl_Socket_OptionDontRoute</code><br> + (sal_Bool) Do not route: send directly to interface. + 1 = do not route , 0 = routing possible + + <li><code>osl_Socket_OptionBroadcast</code><br> + (sal_Bool) Transmission of broadcast messages are allowed on the socket. + 1 = transmission allowed, 0 = transmission disallowed + + <li><code>osl_Socket_OptionUseLoopback</code><br> + + <li><code>osl_Socket_OptionLinger</code><br> + (sal_Int32) Linger on close if unsent data is present. + 0 = linger is off, > 0 = timeout in seconds. + + <li><code>osl_Socket_OptionOOBinLine</code><br> + + + <li><code>osl_Socket_OptionSndBuf</code><br> + (sal_Int32) Size of the send buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing + to the socket. + + <li><code>osl_Socket_OptionRcvBuf</code><br> + (sal_Int32) Size of the receive buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing + to the socket and larger packet sizes. + + <li><code>osl_Socket_OptionSndLowat</code><br> + + <li><code>osl_Socket_OptionRcvLowat</code><br> + + <li><code>osl_Socket_OptionSndTimeo</code><br> + (sal_Int32) Data is sent after this timeout. This allows gathering + of data to send larger packages but increases latency times. + + <li><code>osl_Socket_OptionRcvTimeo</code><br> + + <li><code>osl_Socket_OptionError</code><br> + <li><code>osl_Socket_OptionType</code><br> + + <li><code>osl_Socket_OptionTcpNoDelay</code><br> + Disables the Nagle algorithm for send coalescing. (Do not + collect data until a packet is full, instead send immediately. + This increases network traffic but might improve latency-times.) + 1 = disables the algorithm, 0 = keeps it enabled. + </ul> + If not above mentioned otherwise, the options are only valid for + level <code>osl_Socket_LevelSocket</code>. + + @param pBuffer Pointer to a buffer large enough to take the desired + attribute-value. + + @param BufferLen contains the length of the Buffer. + + @return -1 if an error occurred or else the size of the data copied into + pBuffer. + @see osl_setSocketOption() +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_getSocketOption( oslSocket Socket, + oslSocketOptionLevel Level, + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen); + +/** Sets the sockets attributes. + + @param Socket is the socket to modify. + + @param Level selects the level for which an option should be changed. + Valid values are: + <ul> + <li> osl_sol_socket: Socket Level + <li> osl_sol_tcp: Level of Transmission Control Protocol + </ul> + + @param Option denotes the option to modify. See osl_setSocketOption() for more + details. + + @param pBuffer Pointer to a Buffer which contains the attribute-value. + + @param BufferLen contains the length of the Buffer. + + @return True if the option could be changed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setSocketOption( oslSocket Socket, + oslSocketOptionLevel Level, + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen); + +/** Enables/disables non-blocking-mode of the socket. + @param Socket Change mode for this socket. + @param On <code>sal_True</code> enables non-blocking mode, + <code>sal_False</code> disables non-blocking mode. + @return <code>sal_True</code> if mode could be changed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_enableNonBlockingMode( + oslSocket Socket, sal_Bool On); + + +/** Query state of non-blocking-mode of the socket. + @param Socket Query mode for this socket. + @return True if non-blocking-mode is enabled. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isNonBlockingMode( + oslSocket Socket); + + +/** Queries the socket for its type. + @param[in] Socket The socket to query. + @return one of: + <ul> + <li> osl_Socket_TypeStream + <li> osl_Socket_TypeDgram + <li> osl_Socket_TypeRaw + <li> osl_Socket_TypeRdm + <li> osl_Socket_TypeSeqPacket + <li> osl_invalid_SocketType, if an error occurred + </ul> +*/ +SAL_DLLPUBLIC oslSocketType SAL_CALL osl_getSocketType( + oslSocket Socket); + +/** returns a string which describes the last socket error. + @param[in] Socket The socket to query. + @param[out] strError The string that receives the error message. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_getLastSocketErrorDescription( + oslSocket Socket, rtl_uString **strError); + +/** returns a constant decribing the last error for the socket system. + @return <code>osl_Socket_E_NONE</code> if no error occurred, + <code>osl_invalid_SocketError</code> if an unknown (unmapped) + error occurred, otherwise an enum describing the error. +*/ +SAL_DLLPUBLIC oslSocketError SAL_CALL osl_getLastSocketError( + oslSocket Socket); + +/** Type for the representation of socket sets. +*/ +typedef struct oslSocketSetImpl * oslSocketSet; + +/** Creates a set of sockets to be used with osl_demultiplexSocketEvents(). + @return A oslSocketSet or 0 if creation failed. +*/ +SAL_DLLPUBLIC oslSocketSet SAL_CALL osl_createSocketSet(void); + +/** Destroys a oslSocketSet. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroySocketSet(oslSocketSet Set); + +/** Clears the set from all previously added sockets. + @param Set the set to be cleared. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_clearSocketSet(oslSocketSet Set); + + +/** Adds a socket to the set. + @param Set the set were the socket is added. + @param Socket the socket to be added. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_addToSocketSet(oslSocketSet Set, oslSocket Socket); + +/** Removes a socket from the set. + @param Set the set were the socket is removed from. + @param Socket the socket to be removed. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_removeFromSocketSet(oslSocketSet Set, oslSocket Socket); + +/** Checks if socket is in the set. + @param Set the set to be checked. + @param Socket check if this socket is in the set. + @return <code>sal_True</code> if socket is in the set. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isInSocketSet(oslSocketSet Set, oslSocket Socket); + +/** Checks multiple sockets for events. + @param IncomingSet Checks the sockets in this set + for incoming events (read, accept). If the set is 0, + it is just skipped. + @param OutgoingSet Checks the sockets in this set + for outgoing events (write, connect). If the set is 0, + it is just skipped. + @param OutOfBandSet Checks the sockets in this set + for out-of-band events. If the set is 0, it is just skipped. + @param pTimeout Address of the number of milliseconds to wait for events. If + *pTimeout is -1, the call will block until an event or an error + occurs. + @return -1 on errors, otherwise the number of sockets with + pending events. In case of timeout, the number might be 0. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_demultiplexSocketEvents(oslSocketSet IncomingSet, + oslSocketSet OutgoingSet, + oslSocketSet OutOfBandSet, + const TimeValue* pTimeout); + +/** Closes the socket terminating any ongoing dataflow. + @param[in] Socket The socket to close. + */ +SAL_DLLPUBLIC void SAL_CALL osl_closeSocket(oslSocket Socket); + + +/** Retrieves n bytes from the stream and copies them into pBuffer. + The function avoids incomplete reads due to packet boundaries. + @param[in] Socket The socket to read from. + @param[out] pBuffer receives the read data. + @param[out] nSize the number of bytes to read. pBuffer must be large enough + to hold the n bytes! + @return the number of read bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_readSocket( oslSocket Socket, void *pBuffer, sal_Int32 nSize ); + + +/** Writes n bytes from pBuffer to the stream. The method avoids + incomplete writes due to packet boundaries. + @param[out] Socket The socket to write to. + @param[in] pBuffer contains the data to be written. + @param[in] nSize the number of bytes to write. + @return the number of written bytes. The number will only be smaller than + nSize if an exceptional condition (e.g. connection closed) occurs. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_writeSocket( oslSocket Socket, const void *pBuffer, sal_Int32 nSize ); + +/**@} end section oslSocket +*/ + + + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_SOCKET_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/socket.hxx b/include/osl/socket.hxx new file mode 100644 index 000000000000..f8246c48a448 --- /dev/null +++ b/include/osl/socket.hxx @@ -0,0 +1,559 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef _OSL_SOCKET_HXX_ +#define _OSL_SOCKET_HXX_ + +#include <osl/socket_decl.hxx> + +namespace osl +{ + //______________________________________________________________________________ + inline SocketAddr::SocketAddr() + : m_handle( osl_createEmptySocketAddr( osl_Socket_FamilyInet ) ) + {} + + //______________________________________________________________________________ + inline SocketAddr::SocketAddr(const SocketAddr& Addr) + : m_handle( osl_copySocketAddr( Addr.m_handle ) ) + { + } + + //______________________________________________________________________________ + inline SocketAddr::SocketAddr(oslSocketAddr Addr) + : m_handle( osl_copySocketAddr( Addr ) ) + { + } + + //______________________________________________________________________________ + inline SocketAddr::SocketAddr(oslSocketAddr Addr, __osl_socket_NoCopy ) + : m_handle( Addr ) + { + } + + //______________________________________________________________________________ + inline SocketAddr::SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort) + : m_handle( osl_createInetSocketAddr( strAddrOrHostName.pData, nPort ) ) + { + if(! m_handle ) + { + m_handle = osl_resolveHostname(strAddrOrHostName.pData); + + // host found? + if(m_handle) + { + osl_setInetPortOfSocketAddr(m_handle, nPort); + } + else + { + osl_destroySocketAddr( m_handle ); + m_handle = 0; + } + } + } + + //______________________________________________________________________________ + inline SocketAddr::~SocketAddr() + { + if( m_handle ) + osl_destroySocketAddr( m_handle ); + } + + //______________________________________________________________________________ + inline ::rtl::OUString SocketAddr::getHostname( oslSocketResult *pResult ) const + { + ::rtl::OUString hostname; + oslSocketResult result = osl_getHostnameOfSocketAddr( m_handle, &(hostname.pData) ); + if( pResult ) + *pResult = result; + return hostname; + } + + //______________________________________________________________________________ + inline sal_Int32 SAL_CALL SocketAddr::getPort() const + { + return osl_getInetPortOfSocketAddr(m_handle); + } + + //______________________________________________________________________________ + inline sal_Bool SAL_CALL SocketAddr::setPort( sal_Int32 nPort ) + { + return osl_setInetPortOfSocketAddr(m_handle, nPort ); + } + + inline sal_Bool SAL_CALL SocketAddr::setHostname( const ::rtl::OUString &sDottedIpOrHostname ) + { + *this = SocketAddr( sDottedIpOrHostname , getPort() ); + return is(); + } + + //______________________________________________________________________________ + inline sal_Bool SAL_CALL SocketAddr::setAddr( const ::rtl::ByteSequence & address ) + { + return osl_setAddrOfSocketAddr( m_handle, address.getHandle() ) + == osl_Socket_Ok; + } + + inline ::rtl::ByteSequence SAL_CALL SocketAddr::getAddr( oslSocketResult *pResult ) const + { + ::rtl::ByteSequence sequence; + oslSocketResult result = osl_getAddrOfSocketAddr( m_handle,(sal_Sequence **) &sequence ); + if( pResult ) + *pResult = result; + return sequence; + } + + //______________________________________________________________________________ + inline SocketAddr & SAL_CALL SocketAddr::operator= (oslSocketAddr Addr) + { + oslSocketAddr pNewAddr = osl_copySocketAddr( Addr ); + if( m_handle ) + osl_destroySocketAddr( m_handle ); + m_handle = pNewAddr; + return *this; + } + + //______________________________________________________________________________ + inline SocketAddr & SAL_CALL SocketAddr::operator= (const SocketAddr& Addr) + { + *this = (Addr.getHandle()); + return *this; + } + + inline SocketAddr & SAL_CALL SocketAddr::assign( oslSocketAddr Addr, __osl_socket_NoCopy ) + { + if( m_handle ) + osl_destroySocketAddr( m_handle ); + m_handle = Addr; + return *this; + } + + //______________________________________________________________________________ + inline sal_Bool SAL_CALL SocketAddr::operator== (oslSocketAddr Addr) const + { + return osl_isEqualSocketAddr( m_handle, Addr ); + } + + inline oslSocketAddr SocketAddr::getHandle() const + { + return m_handle; + } + + //______________________________________________________________________________ + inline sal_Bool SocketAddr::is() const + { + return m_handle != 0; + } + + // (static method)______________________________________________________________ + inline ::rtl::OUString SAL_CALL SocketAddr::getLocalHostname( oslSocketResult *pResult ) + { + ::rtl::OUString hostname; + oslSocketResult result = osl_getLocalHostname( &(hostname.pData) ); + if(pResult ) + *pResult = result; + return hostname; + } + + // (static method)______________________________________________________________ + inline void SAL_CALL SocketAddr::resolveHostname( + const ::rtl::OUString & strHostName, SocketAddr &Addr) + { + Addr = SocketAddr( osl_resolveHostname( strHostName.pData ) , SAL_NO_COPY ); + } + + // (static method)______________________________________________________________ + inline sal_Int32 SAL_CALL SocketAddr::getServicePort( + const ::rtl::OUString& strServiceName, + const ::rtl::OUString & strProtocolName ) + { + return osl_getServicePort( strServiceName.pData, strProtocolName.pData ); + } + + //______________________________________________________________________________ + inline Socket::Socket(oslSocketType Type, + oslAddrFamily Family, + oslProtocol Protocol) + : m_handle( osl_createSocket(Family, Type, Protocol) ) + {} + + //______________________________________________________________________________ + inline Socket::Socket( oslSocket socketHandle, __sal_NoAcquire ) + : m_handle( socketHandle ) + {} + + //______________________________________________________________________________ + inline Socket::Socket( oslSocket socketHandle ) + : m_handle( socketHandle ) + { + osl_acquireSocket( m_handle ); + } + + //______________________________________________________________________________ + inline Socket::Socket( const Socket & socket ) + : m_handle( socket.getHandle() ) + { + osl_acquireSocket( m_handle ); + } + + //______________________________________________________________________________ + inline Socket::~Socket() + { + osl_releaseSocket( m_handle ); + } + + //______________________________________________________________________________ + inline Socket& Socket::operator= ( oslSocket socketHandle) + { + osl_acquireSocket( socketHandle ); + osl_releaseSocket( m_handle ); + m_handle = socketHandle; + return *this; + } + + //______________________________________________________________________________ + inline Socket& Socket::operator= (const Socket& sock) + { + return (*this) = sock.getHandle(); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::operator==( const Socket& rSocket ) const + { + return m_handle == rSocket.getHandle(); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::operator==( const oslSocket socketHandle ) const + { + return m_handle == socketHandle; + } + + //______________________________________________________________________________ + inline void Socket::shutdown( oslSocketDirection Direction ) + { + osl_shutdownSocket( m_handle , Direction ); + } + + //______________________________________________________________________________ + inline void Socket::close() + { + osl_closeSocket( m_handle ); + } + + //______________________________________________________________________________ + inline void Socket::getLocalAddr( SocketAddr & addr) const + { + addr.assign( osl_getLocalAddrOfSocket( m_handle ) , SAL_NO_COPY ); + } + + //______________________________________________________________________________ + inline sal_Int32 Socket::getLocalPort() const + { + SocketAddr addr( 0 ); + getLocalAddr( addr ); + return addr.getPort(); + } + + //______________________________________________________________________________ + inline ::rtl::OUString Socket::getLocalHost() const + { + SocketAddr addr( 0 ); + getLocalAddr( addr ); + return addr.getHostname(); + } + + //______________________________________________________________________________ + inline void Socket::getPeerAddr( SocketAddr &addr ) const + { + addr.assign( osl_getPeerAddrOfSocket( m_handle ), SAL_NO_COPY ); + } + + //______________________________________________________________________________ + inline sal_Int32 Socket::getPeerPort() const + { + SocketAddr addr( 0 ); + getPeerAddr( addr ); + return addr.getPort(); + } + + //______________________________________________________________________________ + inline ::rtl::OUString Socket::getPeerHost() const + { + SocketAddr addr( 0 ); + getPeerAddr( addr ); + return addr.getHostname(); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::bind(const SocketAddr& LocalInterface) + { + return osl_bindAddrToSocket( m_handle , LocalInterface.getHandle() ); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::isRecvReady(const TimeValue *pTimeout ) const + { + return osl_isReceiveReady( m_handle , pTimeout ); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::isSendReady(const TimeValue *pTimeout ) const + { + return osl_isSendReady( m_handle, pTimeout ); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::isExceptionPending(const TimeValue *pTimeout ) const + { + return osl_isExceptionPending( m_handle, pTimeout ); + } + + //______________________________________________________________________________ + inline oslSocketType Socket::getType() const + { + return osl_getSocketType( m_handle ); + } + + //______________________________________________________________________________ + inline sal_Int32 Socket::getOption( + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level) const + { + return osl_getSocketOption( m_handle, Level, Option, pBuffer , BufferLen ); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::setOption( oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level ) const + { + return osl_setSocketOption( m_handle, Level, Option , pBuffer, BufferLen ); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::setOption( oslSocketOption option, sal_Int32 nValue ) + { + return setOption( option, &nValue, sizeof( nValue ) ); + } + + //______________________________________________________________________________ + inline sal_Int32 Socket::getOption( oslSocketOption option ) const + { + sal_Int32 n; + getOption( option, &n, sizeof( n ) ); + return n; + } + + //______________________________________________________________________________ + inline sal_Bool Socket::enableNonBlockingMode( sal_Bool bNonBlockingMode) + { + return osl_enableNonBlockingMode( m_handle , bNonBlockingMode ); + } + + //______________________________________________________________________________ + inline sal_Bool Socket::isNonBlockingMode() const + { + return osl_isNonBlockingMode( m_handle ); + } + + //______________________________________________________________________________ + inline void SAL_CALL Socket::clearError() const + { + sal_Int32 err = 0; + getOption(osl_Socket_OptionError, &err, sizeof(err)); + } + + //______________________________________________________________________________ + inline oslSocketError Socket::getError() const + { + return osl_getLastSocketError( m_handle ); + } + + //______________________________________________________________________________ + inline ::rtl::OUString Socket::getErrorAsString( ) const + { + ::rtl::OUString error; + osl_getLastSocketErrorDescription( m_handle, &(error.pData) ); + return error; + } + + //______________________________________________________________________________ + inline oslSocket Socket::getHandle() const + { + return m_handle; + } + + //______________________________________________________________________________ + inline StreamSocket::StreamSocket(oslAddrFamily Family, + oslProtocol Protocol, + oslSocketType Type ) + : Socket( Type, Family, Protocol ) + {} + + //______________________________________________________________________________ + inline StreamSocket::StreamSocket( oslSocket socketHandle, __sal_NoAcquire noacquire ) + : Socket( socketHandle, noacquire ) + {} + + //______________________________________________________________________________ + inline StreamSocket::StreamSocket( oslSocket socketHandle ) + : Socket( socketHandle ) + {} + + //______________________________________________________________________________ + inline StreamSocket::StreamSocket( const StreamSocket & socket ) + : Socket( socket ) + {} + + //______________________________________________________________________________ + inline sal_Int32 StreamSocket::read(void* pBuffer, sal_uInt32 n) + { + return osl_readSocket( m_handle, pBuffer, n ); + } + + //______________________________________________________________________________ + inline sal_Int32 StreamSocket::write(const void* pBuffer, sal_uInt32 n) + { + return osl_writeSocket( m_handle, pBuffer, n ); + } + + + //______________________________________________________________________________ + inline sal_Int32 StreamSocket::recv(void* pBuffer, + sal_uInt32 BytesToRead, + oslSocketMsgFlag Flag) + { + return osl_receiveSocket( m_handle, pBuffer,BytesToRead, Flag ); + } + + //______________________________________________________________________________ + inline sal_Int32 StreamSocket::send(const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag Flag) + { + return osl_sendSocket( m_handle, pBuffer, BytesToSend, Flag ); + } + + //______________________________________________________________________________ + inline ConnectorSocket::ConnectorSocket(oslAddrFamily Family, + oslProtocol Protocol, + oslSocketType Type) + : StreamSocket( Family, Protocol ,Type ) + {} + + //______________________________________________________________________________ + inline oslSocketResult ConnectorSocket::connect( const SocketAddr& TargetHost, + const TimeValue* pTimeout ) + { + return osl_connectSocketTo( m_handle , TargetHost.getHandle(), pTimeout ); + } + + //______________________________________________________________________________ + inline AcceptorSocket::AcceptorSocket(oslAddrFamily Family , + oslProtocol Protocol , + oslSocketType Type ) + : Socket( Type, Family, Protocol ) + {} + + //______________________________________________________________________________ + inline sal_Bool AcceptorSocket::listen(sal_Int32 MaxPendingConnections) + { + return osl_listenOnSocket( m_handle, MaxPendingConnections ); + } + + //______________________________________________________________________________ + inline oslSocketResult AcceptorSocket::acceptConnection( StreamSocket& Connection) + { + oslSocket o = osl_acceptConnectionOnSocket( m_handle, 0 ); + oslSocketResult status = osl_Socket_Ok; + if( o ) + { + Connection = StreamSocket( o , SAL_NO_ACQUIRE ); + } + else + { + Connection = StreamSocket(); + status = osl_Socket_Error; + } + return status; + } + + //______________________________________________________________________________ + inline oslSocketResult AcceptorSocket::acceptConnection( + StreamSocket& Connection, SocketAddr & PeerAddr) + { + // TODO change in/OUT parameter + oslSocket o = osl_acceptConnectionOnSocket( m_handle, (oslSocketAddr *)&PeerAddr ); + oslSocketResult status = osl_Socket_Ok; + if( o ) + { + Connection = StreamSocket( o , SAL_NO_ACQUIRE ); + } + else + { + Connection = StreamSocket(); + status = osl_Socket_Error; + } + return status; + } + + //______________________________________________________________________________ + inline DatagramSocket::DatagramSocket(oslAddrFamily Family, + oslProtocol Protocol, + oslSocketType Type) + : Socket( Type, Family, Protocol ) + {} + + //______________________________________________________________________________ + inline sal_Int32 DatagramSocket::recvFrom(void* pBuffer, + sal_uInt32 BufferSize, + SocketAddr* pSenderAddr, + oslSocketMsgFlag Flag ) + { + sal_Int32 nByteRead; + if( pSenderAddr ) + { + // TODO : correct the out-parameter pSenderAddr outparameter + nByteRead = osl_receiveFromSocket( m_handle, pSenderAddr->getHandle() , pBuffer, + BufferSize, Flag); +// nByteRead = osl_receiveFromSocket( m_handle, *(oslSocketAddr**) &pSenderAddr , pBuffer, +// BufferSize, Flag); + } + else + { + nByteRead = osl_receiveFromSocket( m_handle, 0 , pBuffer , BufferSize , Flag ); + } + return nByteRead; + } + + //______________________________________________________________________________ + inline sal_Int32 DatagramSocket::sendTo( const SocketAddr& ReceiverAddr, + const void* pBuffer, + sal_uInt32 BufferSize, + oslSocketMsgFlag Flag ) + { + return osl_sendToSocket( m_handle, ReceiverAddr.getHandle(), pBuffer, BufferSize, Flag ); + } +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/socket_decl.hxx b/include/osl/socket_decl.hxx new file mode 100644 index 000000000000..f51cca12e4c3 --- /dev/null +++ b/include/osl/socket_decl.hxx @@ -0,0 +1,721 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_SOCKET_DECL_HXX_ +#define _OSL_SOCKET_DECL_HXX_ + +#include <osl/socket.h> +#include <rtl/ustring.hxx> +#include <rtl/byteseq.hxx> + +namespace osl +{ + enum __osl_socket_NoCopy { SAL_NO_COPY }; + + /** The class should be understood as a reference to a socket address handle ( struct sockaddr ). + + The handle is mutable. + */ + class SocketAddr + { + protected: + oslSocketAddr m_handle; + public: + + /** Creates socket address of unknown type. + */ + inline SocketAddr(); + + /** Copy constructor. + */ + inline SocketAddr(const SocketAddr& Addr); + + /** The SocketAddr takes over the responsibility of the handle ( which means, + that the handle gets destructed by the destructor of this reference) + @param nocopy use SAL_NO_COPY + */ + inline SocketAddr(const oslSocketAddr , __osl_socket_NoCopy nocopy ); + + /** Copyconstructs the oslSocketAddr handle. + */ + inline SocketAddr(oslSocketAddr Addr); + + /** tcpip-specif constructor. + @param strAddrOrHostName strAddrOrHostName hostname or dotted ip-number of the network + interface, the socket shall be created on. + @param nPort tcp-ip port number + */ + inline SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort ); + + /** destroys underlying oslSocketAddress + */ + inline ~SocketAddr(); + + /** checks, if the SocketAddr was created successful. + @return <code>sal_True</code> if there is a valid underlying handle, + otherwise sal_False. + */ + inline sal_Bool is() const; + + /** Converts the address to a (human readable) domain-name. + + @param pResult 0, if you are not interested in errors, + otherwise *pResult contains an error code on failure + or osl_Socket_Ok on success + @return the hostname of this SocketAddr or an empty string on failure. + @see osl_getHostnameOfSocketAddr() + */ + inline ::rtl::OUString SAL_CALL getHostname( oslSocketResult *pResult = 0 ) const; + + /** Sets the ipaddress or hostname of the SocketAddress + */ + inline sal_Bool SAL_CALL setHostname( const ::rtl::OUString &sDottedIpOrHostname ); + + /** Returns the port number of the address. + @return the port in host-byte order or or OSL_INVALID_PORT on errors. + */ + inline sal_Int32 SAL_CALL getPort() const; + + /** Sets the port number of the address. + @return true if successfule. + */ + inline sal_Bool SAL_CALL setPort( sal_Int32 nPort ); + + /** Sets the address of the underlying socket address struct in network byte order. + @return true on success, false signales falure. + */ + inline sal_Bool SAL_CALL setAddr( const ::rtl::ByteSequence & address ); + + /** Returns the address of the underlying socket in network byte order + */ + inline ::rtl::ByteSequence SAL_CALL getAddr( oslSocketResult *pResult = 0 ) const; + + /** assign the handle to this reference. The previous handle is released. + */ + inline SocketAddr & SAL_CALL operator= (oslSocketAddr Addr); + + /** + */ + inline SocketAddr & SAL_CALL operator= (const SocketAddr& Addr); + + /** Assigns the socket addr without copyconstructing it. + @param Addr the socket address. + @param nocopy use SAL_NO_COPY + */ + inline SocketAddr & SAL_CALL assign( oslSocketAddr Addr, __osl_socket_NoCopy nocopy ); + + /** Returns true if the underlying handle is identical to the Addr handle. + */ + inline sal_Bool SAL_CALL operator== (oslSocketAddr Addr) const; + + /** Returns true if the underlying handle is identical to the Addr handle. + */ + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + + /** Returns the underlying SocketAddr handle without copyconstructing it. + */ + inline oslSocketAddr SAL_CALL getHandle() const; + + /** Get the hostname for the local interface. + @param pResult after the call *pResult contains osl_Socket_Ok on success or + an error on failure. + @return the hostname + */ + static inline ::rtl::OUString SAL_CALL getLocalHostname( oslSocketResult *pResult = 0); + + /** Tries to find an address for a host. + @see osl_resolveHostname() + @return A new created socket-address or 0 if the name could not be found. + */ + static inline void SAL_CALL resolveHostname( + const ::rtl::OUString & strHostName , SocketAddr & Addr ); + + /** + Tries to find the port associated with the given service/protocol- + pair (e.g. "ftp"/"tcp"). + @return the port number in host-byte order or <code>OSL_INVALID_PORT</code> + if no service/protocol pair could be found. + */ + static inline sal_Int32 SAL_CALL getServicePort( + const ::rtl::OUString& strServiceName, + const ::rtl::OUString & strProtocolName= ::rtl::OUString("tcp") ); + }; + + + class Socket + { + protected: + oslSocket m_handle; + protected: + /** Creates a socket. Note it's protected. + @param Type + @param Family + @param Protocol + */ + inline Socket(oslSocketType Type, + oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp); + public: + inline Socket( ); + + inline Socket( const Socket & socket ); + + inline Socket( oslSocket socketHandle ); + + /** The instance takes over the handle's ownership without acquiring the + handle, but releases it within the dtor. + @param socketHandle the handle + @param noacquire use SAL_NO_ACQUIRE + */ + inline Socket( oslSocket socketHandle, __sal_NoAcquire noacquire ); + + /** Destructor. Releases the underlying handle + */ + inline ~Socket(); + + /** Assignment operator. If socket was already created, the old one will + be discarded. + */ + inline Socket& SAL_CALL operator= ( oslSocket socketHandle); + + /** Assignment operator. If socket was already created, the old one will + be discarded. + */ + inline Socket& SAL_CALL operator= (const Socket& sock); + + /** + @return <code>sal_True</code>, when the underlying handle of both + Socket instances are identical, <code>sal_False</code> otherwise. + */ + inline sal_Bool SAL_CALL operator==( const Socket& rSocket ) const ; + + /** + @return <code>sal_True</code>, when the underlying handle of both + Socket instances are identical, <code>sal_False</code> otherwise. + */ + inline sal_Bool SAL_CALL operator==( const oslSocket socketHandle ) const; + + /** Closes a definite or both directions of the bidirectional stream. + + @param Direction + @see osl_shutdownSocket() + */ + inline void SAL_CALL shutdown( oslSocketDirection Direction = osl_Socket_DirReadWrite ); + + /** Closes a socket. + Note that closing a socket is identical to shutdown( osl_Socket_DirReadWrite ), + as the operating system distinguish both cases, both functions or offered in this API. + @see osl_closeSocket() + */ + inline void SAL_CALL close(); + + /** Retrieves the address of the local interface of this socket. + @param Addr [out] receives the address. + @see osl_getLocalAddrOfSocket() + */ + inline void SAL_CALL getLocalAddr( SocketAddr &Addr ) const; + + /** Get the local port of the socket. Usually used after bind(). + @return the port number or OSL_INVALID_PORT on errors. + */ + inline sal_Int32 SAL_CALL getLocalPort() const; + + /** Get the hostname for the local interface. + @return the hostname or an empty string (""). + */ + inline ::rtl::OUString SAL_CALL getLocalHost() const; + + /** Retrieves the address of the remote host of this socket. + @param Addr [out] receives the address. + */ + inline void SAL_CALL getPeerAddr( SocketAddr & Addr) const; + + /** Get the remote port of the socket. + @return the port number or OSL_INVALID_PORT on errors. + */ + inline sal_Int32 SAL_CALL getPeerPort() const; + + /** Get the hostname for the remote interface. + @return the hostname or an empty string (""). + */ + inline ::rtl::OUString SAL_CALL getPeerHost() const; + + /** Binds the socket to the specified (local) interface. + @param LocalInterface Address of the Interface + @return True if bind was successful. + */ + inline sal_Bool SAL_CALL bind(const SocketAddr& LocalInterface); + + /** Checks if read operations will block. + + You can specify a timeout-value in seconds/nanoseconds that denotes + how the operation will block if the Socket is not ready. + @return <code>sal_True</code> if read operations (recv, recvFrom, accept) on the Socket + will NOT block; <code>sal_False</code> if it would block or if an error occurred. + + @param pTimeout if 0, the operation will block without a timeout. Otherwise + the specified amout of time. + */ + inline sal_Bool SAL_CALL isRecvReady(const TimeValue *pTimeout = 0) const; + + /** Checks if send operations will block. + + You can specify a timeout-value in seconds/nanoseconds that denotes + how the operation will block if the Socket is not ready. + @return <code>sal_True</code> if send operations (send, sendTo) on the Socket + will NOT block; <code>sal_False</code> if it would block or if an error occurred. + + @param pTimeout if 0, the operation will block without a timeout. Otherwise + the specified amout of time. + */ + inline sal_Bool SAL_CALL isSendReady(const TimeValue *pTimeout = 0) const; + + + /** Checks if a request for out-of-band data will block. + + You can specify a timeout-value in seconds/nanoseconds that denotes + how the operation will block if the Socket has no pending OOB data. + + @return <code>sal_True</code> if OOB-request operations (recv with appropriate flags) + on the Socket will NOT block; <code>sal_False</code> if it would block or if + an error occurred. + + @param pTimeout if 0, the operation will block without a timeout. Otherwise + the specified amout of time. + */ + inline sal_Bool SAL_CALL isExceptionPending(const TimeValue *pTimeout = 0) const; + + + /** Queries the socket for its type. + @return one of: + <ul> + <li> <code>osl_Socket_TypeStream</code> + <li> <code>osl_Socket_TypeDgram</code> + <li> <code>osl_Socket_TypeRaw</code> + <li> <code>osl_Socket_TypeRdm</code> + <li> <code>osl_Socket_TypeSeqPacket</code> + <li> <code>osl_invalid_SocketType</code>, if an error occurred + </ul> + */ + inline oslSocketType SAL_CALL getType() const; + + /** Retrieves option-attributes associated with the socket. + @param Option The attribute to query. + Valid values (depending on the Level) are: + <ul> + <li> <code>osl_Socket_Option_Debug</code><br> + (sal_Bool) Socket debug flag 1 = enabled, 0 = disabled. + + <li> <code>osl_Socket_OptionAcceptConn</code><br> + <li> <code>osl_Socket_OptionReuseAddr</code><br> + (sal_Bool) Allows the socket to be bound to an address that is + already in use. + 1 = multiple bound allowed, 0 = no multiple bounds allowed + + <li><code>osl_Socket_OptionKeepAlive</code><br> + (sal_Bool) Keepalive packets are sent by the underlying socket. + 1 = enabled, 0 = disabled + + <li><code>osl_Socket_OptionDontRoute</code><br> + (sal_Bool) Do not route: send directly to interface. + 1 = do not route , 0 = routing possible + + <li><code>osl_Socket_OptionBroadcast</code><br> + (sal_Bool) Transmission of broadcast messages are allowed on the socket. + 1 = transmission allowed, 0 = transmission disallowed + + <li><code>osl_Socket_OptionUseLoopback</code><br> + + <li><code>osl_Socket_OptionLinger</code><br> + (linger) Linger on close if unsent data is present. + linger has two members: l_onoff, l_linger + l_onoff = 0 is off, l_onoff > 0 and l_linger= timeout in seconds. + + <li><code>osl_Socket_OptionOOBinLine</code><br> + + + <li><code>osl_Socket_OptionSndBuf</code><br> + (sal_Int32) Size of the send buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing + to the socket. + + <li><code>osl_Socket_OptionRcvBuf</code><br> + (sal_Int32) Size of the receive buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing + to the socket and larger packet sizes. + + <li><code>osl_Socket_OptionSndLowat</code><br> + + <li><code>osl_Socket_OptionRcvLowat</code><br> + + <li><code>osl_Socket_OptionSndTimeo</code><br> + (sal_Int32) Data is sent after this timeout. This allows gathering + of data to send larger packages but increases latency times. + + <li><code>osl_Socket_OptionRcvTimeo</code><br> + + <li><code>osl_Socket_OptionError</code><br> + <li><code>osl_Socket_OptionType</code><br> + + <li><code>osl_Socket_OptionTcpNoDelay</code><br> + Disables the Nagle algorithm for send coalescing. (Do not + collect data until a packet is full, instead send immediately. + This increases network traffic but might improve latency-times.) + 1 = disables the algorithm, 0 = keeps it enabled. + </ul> + + If not above mentioned otherwise, the options are only valid for + level <code>osl_Socket_LevelSocket</code>. + @param pBuffer The Buffer will be filled with the attribute. + + @param BufferLen The size of pBuffer. + + @param Level The option level. + + Valid values are: + <ul> + <li><code>osl_Socket_LevelSocket</code> : Socket Level + <li><code>osl_Socket_LevelTcp</code> : Level of Transmission Control Protocol + </ul> + @return The size of the attribute copied into pBuffer or -1 if an error + occurred. + */ + inline sal_Int32 SAL_CALL getOption( + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket) const; + + /** Sets the sockets attributes. + + @param Option denotes the option to modify. + Valid values (depending on the Level) are: + <ul> + <li> osl_Socket_Option_Debug + <li> osl_Socket_OptionAcceptConn + <li> osl_Socket_OptionReuseAddr + <li> osl_Socket_OptionKeepAlive + <li> osl_Socket_OptionDontRoute + <li> osl_Socket_OptionBroadcast + <li> osl_Socket_OptionUseLoopback + <li> osl_Socket_OptionLinger + <li> osl_Socket_OptionOOBinLine + <li> osl_Socket_OptionSndBuf + <li> osl_Socket_OptionRcvBuf + <li> osl_Socket_OptionSndLowat + <li> osl_Socket_OptionRcvLowat + <li> osl_Socket_OptionSndTimeo + <li> osl_Socket_OptionRcvTimeo + <li> osl_Socket_OptionError + <li> osl_Socket_OptionType + <li> osl_Socket_OptionTcpNoDelay + </ul> + + If not above mentioned otherwise, the options are only valid for + level osl_Socket_LevelSocket. + + @param pBuffer Pointer to a Buffer which contains the attribute-value. + + @param BufferLen contains the length of the Buffer. + + @param Level selects the level for which an option should be changed. + Valid values are: + <ul> + <li> osl_Socket_evel_Socket : Socket Level + <li> osl_Socket_Level_Tcp : Level of Transmission Control Protocol + </ul> + + @return True if the option could be changed. + */ + inline sal_Bool SAL_CALL setOption( oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket ) const; + + /** Convenience function for setting sal_Bool and sal_Int32 option values. + @see setOption() + */ + inline sal_Bool setOption( oslSocketOption option, sal_Int32 nValue ); + + /** Convenience function for retrieving sal_Bool and sal_Int32 option values. + @see setOption() + */ + inline sal_Int32 getOption( oslSocketOption option ) const; + + /** Enables/disables non-blocking mode of the socket. + @param bNonBlockingMode If <code>sal_True</code>, blocking mode will be switched off + If <code>sal_False</code>, the socket will become a blocking + socket (which is the default behaviour of a socket). + @return <code>sal_True</code> if mode could be set. + */ + inline sal_Bool SAL_CALL enableNonBlockingMode( sal_Bool bNonBlockingMode); + + /** Query blocking mode of the socket. + @return <code>sal_True</code> if non-blocking mode is set. + */ + inline sal_Bool SAL_CALL isNonBlockingMode() const; + + + /** clears the error status + */ + inline void SAL_CALL clearError() const; + + /** returns a constant decribing the last error for the socket system. + + @return osl_Socket_E_NONE if no error occurred, invalid_SocketError if + an unknown (unmapped) error occurred, otherwise an enum describing the + error. + @see osl_getLastSocketError() + */ + inline oslSocketError getError() const; + + /** Builds a string with the last error-message for the socket. + */ + inline ::rtl::OUString getErrorAsString( ) const; + + /** Returns the underlying handle unacquired (The caller must acquire it to keep it). + */ + inline oslSocket getHandle() const; + }; + + + class StreamSocket : public Socket + { + public: + /** Creates a socket. + @param Family the Family of the socket (Inet by default) + @param Protocol the Protocon of the socket (IP by default) + @param Type For some protocols it might be desirable to + use a different type than <code>osl_Socket_TypeStream</code> + (like <code>osl_Socket_TypeSeqPacket</code>). + Therefore this parameter is not hidden. + */ + inline StreamSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + inline StreamSocket( const StreamSocket & ); + + inline StreamSocket( oslSocket Socket , __sal_NoAcquire noacquire ); + + inline StreamSocket( oslSocket Socket ); + + /** Retrieves n bytes from the stream and copies them into pBuffer. + The method avoids incomplete reads due to packet boundaries and is thus + blocking. + @param pBuffer receives the read data. pBuffer must be large enough + to hold n bytes. + @param n the number of bytes to read. + @return the number of read bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + inline sal_Int32 SAL_CALL read(void* pBuffer, sal_uInt32 n); + + /** Writes n bytes from pBuffer to the stream. The method avoids + incomplete writes due to packet boundaries and is thus blocking. + @param pBuffer contains the data to be written. + @param n the number of bytes to write. + @return the number of written bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + inline sal_Int32 SAL_CALL write(const void* pBuffer, sal_uInt32 n); + + + /** Tries to receive BytesToRead data from the connected socket, + + @param[out] pBuffer Points to a buffer that will be filled with the received + data. pBuffer must have at least have a size of BytesToRead. + @param[in] BytesToRead The number of bytes to read. + @param[in] flags Modifier for the call. Valid values are: + + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + @return the number of received bytes, which may be less than BytesToRead. + */ + inline sal_Int32 SAL_CALL recv(void* pBuffer, + sal_uInt32 BytesToRead, + oslSocketMsgFlag flags= osl_Socket_MsgNormal); + + /** Tries to send BytesToSend data to the connected socket. + + @param pBuffer [in] Points to a buffer that contains the send-data. + @param BytesToSend [in] The number of bytes to send. pBuffer must have at least + this size. + @param Flag [in] Modifier for the call. Valid values are: + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of transfered bytes. It may be less than BytesToSend. + */ + sal_Int32 SAL_CALL send(const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag= osl_Socket_MsgNormal); + }; + + class ConnectorSocket : public StreamSocket + { + public: + /** Creates a socket that can connect to a (remote) host. + @param Family the Family of the socket (Inet by default) + @param Protocol the Protocon of the socket (IP by default) + @param Type For some protocols it might be desirable to + use a different type than sock_stream <code>osl_Socket_TypeSeqPacket</code> + (like <code>osl_Socket_TypeSeqPacket</code>). + Therefore we do not hide this parameter here. + */ + ConnectorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + + /** Connects the socket to a (remote) host. + @param TargetHost The address of the target. + @param pTimeout The timeout for blocking. If 0, a default system dependent timeout + us used. + @return <code> osl_Socket_Ok</code> if connected successfully, + <code>osl_Socket_TimedOut</code> on timeout, + <code>osl_Socket_Interrupted</code> if unblocked forcefully (by osl::Socket::close()), + <code>osl_Socket_Error</code> if connect failed. + */ + oslSocketResult SAL_CALL connect(const SocketAddr& TargetHost, const TimeValue* pTimeout = 0); + }; + + /** Allows to accept socket connections. + */ + class AcceptorSocket : public Socket + { + public: + inline AcceptorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + /** Prepare a socket for the accept-call. The socket must have been + bound before to the local address. + @param MaxPendingConnections The maximum number of pending + connections (waiting to be accepted) on this socket. If you use + -1, a system default value is used. + @return <code>sal_True</code> if call was successful. + */ + inline sal_Bool SAL_CALL listen(sal_Int32 MaxPendingConnections= -1); + + /** Accepts incoming connections on the socket. You must + precede this call with osl::Socket::bind() and listen(). + @param Connection receives the incoming connection. + @return <code>osl_Socket_Ok</code>, if a connection has been accepted, + <code>osl_Socket_TimedOut</code>, if m_RecvTimeout milliseconds passed without connect, + <code>osl_Socket_Error</code> on errors. + */ + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection); + + /** Accepts incoming connections on the socket. You must + precede this call with osl::Socket::bind() and listen(). + @param PeerAddr receives the address of the connecting entity + (your communication partner). + @param Connection receives the incoming connection. + @return <code>osl_Socket_Ok</code>, if a connection has been accepted, + <code>osl_Socket_TimedOut</code>, if m_RecvTimeout milliseconds passed without connect, + <code>osl_Socket_Error</code> on errors. + */ + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection, SocketAddr & PeerAddr); + }; + + + + /** A connectionless socket to send and receive datagrams. + */ + class DatagramSocket : public Socket + { + public: + + /** Creates a datagram socket. + @param Family the Family of the socket (Inet by default) + @param Protocol the Protocon of the socket (IP by default) + @param Type is sock_dgram by default. + */ + inline DatagramSocket(oslAddrFamily Family= osl_Socket_FamilyInet, + oslProtocol Protocol= osl_Socket_ProtocolIp, + oslSocketType Type= osl_Socket_TypeDgram); + + /** Tries to receives BufferSize data from the socket, if no error occurs. + + @param pSenderAddr [out] You must provide pointer to a SocketAddr. + It will be filled with the address of the datagrams sender. + If pSenderAddr is 0, it is ignored. + @param pBuffer [out] Points to a buffer that will be filled with the received + datagram. + @param BufferSize [in] The size of pBuffer. + @param Flag [in] Modifier for the call. Valid values are: + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of received bytes. + */ + inline sal_Int32 SAL_CALL recvFrom(void* pBuffer, + sal_uInt32 BufferSize, + SocketAddr* pSenderAddr= 0, + oslSocketMsgFlag Flag= osl_Socket_MsgNormal); + + /** Tries to send one datagram with BytesToSend size to the given ReceiverAddr. + Since there is only send one packet, the function doesn't care about + packet boundaries. + + @param ReceiverAddr [in] A SocketAddr that contains + the destination address for this send. + + @param pBuffer [in] Points to a buffer that contains the send-data. + @param BufferSize [in] The number of bytes to send. pBuffer must have at least + this size. + @param Flag [in] Modifier for the call. Valid values are: + + <ul> + <li><code>osl_Socket_MsgNormal</code> + <li><code>osl_Socket_MsgOOB</code> + <li><code>osl_Socket_MsgPeek</code> + <li><code>osl_Socket_MsgDontRoute</code> + <li><code>osl_Socket_MsgMaxIOVLen</code> + </ul> + + @return the number of transfered bytes. + */ + inline sal_Int32 SAL_CALL sendTo( const SocketAddr& ReceiverAddr, + const void* pBuffer, + sal_uInt32 BufferSize, + oslSocketMsgFlag Flag= osl_Socket_MsgNormal); + }; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/thread.h b/include/osl/thread.h new file mode 100644 index 000000000000..bc93a57b1735 --- /dev/null +++ b/include/osl/thread.h @@ -0,0 +1,196 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_THREAD_H_ +#define _OSL_THREAD_H_ + +#include "sal/config.h" + +#include "osl/time.h" +#include "rtl/textenc.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Opaque data type for threads. As with all other osl-handles + you can initialize and/or test it to/for 0. +*/ +typedef void* oslThread; + +/** the function-ptr. representing the threads worker-function. +*/ +typedef void (SAL_CALL *oslWorkerFunction)(void*); + +/** levels of thread-priority + Note that oslThreadPriorityUnknown might be returned + by getPriorityOfThread() (e.g. when it is terminated), + but mustn't be used with setPriority()! +*/ +typedef enum +{ + osl_Thread_PriorityHighest, + osl_Thread_PriorityAboveNormal, + osl_Thread_PriorityNormal, + osl_Thread_PriorityBelowNormal, + osl_Thread_PriorityLowest, + osl_Thread_PriorityUnknown, /* don't use to set */ + osl_Thread_Priority_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslThreadPriority; + + +typedef sal_uInt32 oslThreadIdentifier; + +typedef void* oslThreadKey; + +/** Create the thread, using the function-ptr pWorker as + its main (worker) function. This functions receives in + its void* parameter the value supplied by pThreadData. + Once the OS-structures are initialized,the thread starts + running. + @return 0 if creation failed, otherwise a handle to the thread +*/ +SAL_DLLPUBLIC oslThread SAL_CALL osl_createThread(oslWorkerFunction pWorker, void* pThreadData); + +/** Create the thread, using the function-ptr pWorker as + its main (worker) function. This functions receives in + its void* parameter the value supplied by pThreadData. + The thread will be created, but it won't start running. + To wake-up the thread, use resume(). + @return 0 if creation failed, otherwise a handle to the thread +*/ +SAL_DLLPUBLIC oslThread SAL_CALL osl_createSuspendedThread(oslWorkerFunction pWorker, void* pThreadData); + +/** Get the identifier for the specified thread or if parameter + Thread is NULL of the current active thread. + @return identifier of the thread +*/ +SAL_DLLPUBLIC oslThreadIdentifier SAL_CALL osl_getThreadIdentifier(oslThread Thread); + +/** Release the thread handle. + If Thread is NULL, the function won't do anything. + Note that we do not interfere with the actual running of + the thread, we just free up the memory needed by the handle. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyThread(oslThread Thread); + +/** Wake-up a thread that was suspended with suspend() or + createSuspended(). The oslThread must be valid! +*/ +SAL_DLLPUBLIC void SAL_CALL osl_resumeThread(oslThread Thread); + +/** Suspend the execution of the thread. If you want the thread + to continue, call resume(). The oslThread must be valid! +*/ +SAL_DLLPUBLIC void SAL_CALL osl_suspendThread(oslThread Thread); + +/** Changes the threads priority. + The oslThread must be valid! +*/ +SAL_DLLPUBLIC void SAL_CALL osl_setThreadPriority(oslThread Thread, oslThreadPriority Priority); + +/** Retrieves the threads priority. + Returns oslThreadPriorityUnknown for invalid Thread-argument or + terminated thread. (I.e.: The oslThread might be invalid.) +*/ +SAL_DLLPUBLIC oslThreadPriority SAL_CALL osl_getThreadPriority(const oslThread Thread); + +/** Returns True if the thread was created and has not terminated yet. + Note that according to this definition a "running" thread might be + suspended! Also returns False is Thread is NULL. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isThreadRunning(const oslThread Thread); + +/** Blocks the calling thread until Thread has terminated. + Returns immediately if Thread is NULL. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_joinWithThread(oslThread Thread); + +/** Blocks the calling thread at least for the given number + of time. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_waitThread(const TimeValue* pDelay); + +/** The requested thread will get terminate the next time + scheduleThread() is called. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_terminateThread(oslThread Thread); + +/** Offers the rest of the threads time-slice to the OS. + scheduleThread() should be called in the working loop + of the thread, so any other thread could also get the + processor. Returns False if the thread should terminate, so + the thread could free any allocated resources. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_scheduleThread(oslThread Thread); + +/** Offers the rest of the threads time-slice to the OS. + Under POSIX you _need_ to yield(), otherwise, since the + threads are not preempted during execution, NO other thread + (even with higher priority) gets the processor. Control is + only given to another thread if the current thread blocks + or uses yield(). +*/ +SAL_DLLPUBLIC void SAL_CALL osl_yieldThread(void); + +/** Attempts to set the name of the current thread. + + The name of a thread is usually evaluated for debugging purposes. Not all + platforms support this. On Linux, a set thread name can be observed with + "ps -L". On Windows with the Microsoft compiler, a thread name set while a + debugger is attached can be observed within the debugger. + + @param name the name of the thread; must not be null; on Linux, only the + first 16 characters are used +*/ +SAL_DLLPUBLIC void SAL_CALL osl_setThreadName(char const * name); + +/* Callback when data stored in a thread key is no longer needed */ + +typedef void (SAL_CALL *oslThreadKeyCallbackFunction)(void *); + +/** Create a key to an associated thread local storage pointer. */ +SAL_DLLPUBLIC oslThreadKey SAL_CALL osl_createThreadKey(oslThreadKeyCallbackFunction pCallback); + +/** Destroy a key to an associated thread local storage pointer. */ +SAL_DLLPUBLIC void SAL_CALL osl_destroyThreadKey(oslThreadKey Key); + +/** Get to key associated thread specific data. */ +SAL_DLLPUBLIC void* SAL_CALL osl_getThreadKeyData(oslThreadKey Key); + +/** Set to key associated thread specific data. */ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setThreadKeyData(oslThreadKey Key, void *pData); + +/** Get the current thread local text encoding. */ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL osl_getThreadTextEncoding(void); + +/** Set the thread local text encoding. + @return the old text encoding. +*/ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL osl_setThreadTextEncoding(rtl_TextEncoding Encoding); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_THREAD_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/thread.hxx b/include/osl/thread.hxx new file mode 100644 index 000000000000..3a1b73e829ef --- /dev/null +++ b/include/osl/thread.hxx @@ -0,0 +1,238 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _THREAD_HXX_ +#define _THREAD_HXX_ + +#include "sal/config.h" + +#include <cassert> + +#include <osl/time.h> + + +#include <osl/diagnose.h> +#include <osl/thread.h> +#include <rtl/alloc.h> + +namespace osl +{ +/** threadFunc is the function which is executed by the threads + created by the osl::Thread class. The function's signature + matches the one of oslWorkerFunction which is declared in + osl/thread.h . +*/ +extern "C" inline void SAL_CALL threadFunc( void* param); + +/** + A thread abstraction. + + @deprecated use ::salhelper::Thread instead. Only the static member + functions ::osl::Thread::getCurrentIdentifier, ::osl::Thread::wait, and + ::osl::Thread::yield are not deprecated. + */ +class Thread +{ + Thread( const Thread& ); + Thread& operator= ( const Thread& ); +public: + // these are here to force memory de/allocation to sal lib. + inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW (()) + { return ::rtl_allocateMemory( nSize ); } + inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW (()) + { ::rtl_freeMemory( pMem ); } + inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW (()) + { return pMem; } + inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW (()) + {} + + Thread(): m_hThread(0){} + + virtual ~Thread() + { + osl_destroyThread( m_hThread); + } + + sal_Bool SAL_CALL create() + { + assert(m_hThread == 0); // only one running thread per instance + m_hThread = osl_createSuspendedThread( threadFunc, (void*)this); + if (m_hThread == 0) + { + return false; + } + osl_resumeThread(m_hThread); + return true; + } + + sal_Bool SAL_CALL createSuspended() + { + assert(m_hThread == 0); // only one running thread per instance + if( m_hThread) + return sal_False; + m_hThread= osl_createSuspendedThread( threadFunc, + (void*)this); + return m_hThread != 0; + } + + virtual void SAL_CALL suspend() + { + if( m_hThread ) + osl_suspendThread(m_hThread); + } + + virtual void SAL_CALL resume() + { + if( m_hThread ) + osl_resumeThread(m_hThread); + } + + virtual void SAL_CALL terminate() + { + if( m_hThread ) + osl_terminateThread(m_hThread); + } + + virtual void SAL_CALL join() + { + osl_joinWithThread(m_hThread); + } + + sal_Bool SAL_CALL isRunning() const + { + return osl_isThreadRunning(m_hThread); + } + + void SAL_CALL setPriority( oslThreadPriority Priority) + { + if( m_hThread ) + osl_setThreadPriority(m_hThread, Priority); + } + + oslThreadPriority SAL_CALL getPriority() const + { + return m_hThread ? osl_getThreadPriority(m_hThread) : osl_Thread_PriorityUnknown; + } + + oslThreadIdentifier SAL_CALL getIdentifier() const + { + return osl_getThreadIdentifier(m_hThread); + } + + static oslThreadIdentifier SAL_CALL getCurrentIdentifier() + { + return osl_getThreadIdentifier(0); + } + + static void SAL_CALL wait(const TimeValue& Delay) + { + osl_waitThread(&Delay); + } + + static void SAL_CALL yield() + { + osl_yieldThread(); + } + + static inline void setName(char const * name) throw () { + osl_setThreadName(name); + } + + virtual sal_Bool SAL_CALL schedule() + { + return m_hThread ? osl_scheduleThread(m_hThread) : sal_False; + } + + SAL_CALL operator oslThread() const + { + return m_hThread; + } + +protected: + + /** The thread functions calls the protected functions + run and onTerminated. + */ + friend void SAL_CALL threadFunc( void* param); + + virtual void SAL_CALL run() = 0; + + virtual void SAL_CALL onTerminated() + { + } + +private: + oslThread m_hThread; +}; + +extern "C" inline void SAL_CALL threadFunc( void* param) +{ + Thread* pObj= (Thread*)param; + pObj->run(); + pObj->onTerminated(); +} + +class ThreadData +{ + ThreadData( const ThreadData& ); + ThreadData& operator= (const ThreadData& ); +public: + /// Create a thread specific local data key + ThreadData( oslThreadKeyCallbackFunction pCallback= 0 ) + { + m_hKey = osl_createThreadKey( pCallback ); + } + + /// Destroy a thread specific local data key + ~ThreadData() + { + osl_destroyThreadKey(m_hKey); + } + + /** Set the data associated with the data key. + @returns True if operation was successful + */ + sal_Bool SAL_CALL setData(void *pData) + { + return (osl_setThreadKeyData(m_hKey, pData)); + } + + /** Get the data associated with the data key. + @returns The data asscoitaed with the data key or + NULL if no data was set + */ + void* SAL_CALL getData() + { + return osl_getThreadKeyData(m_hKey); + } + + operator oslThreadKey() const + { + return m_hKey; + } + +private: + oslThreadKey m_hKey; +}; + +} // end namespace osl + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/time.h b/include/osl/time.h new file mode 100644 index 000000000000..4be9e7278419 --- /dev/null +++ b/include/osl/time.h @@ -0,0 +1,159 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef _OSL_TIME_H_ +#define _OSL_TIME_H_ + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************/ +/* TimeValue */ +/****************************************************************************/ + +#ifdef SAL_W32 +# pragma pack(push, 8) +#endif + +/* Time since Jan-01-1970 */ + +typedef struct { + sal_uInt32 Seconds; + sal_uInt32 Nanosec; +} TimeValue; + +#if defined(SAL_W32) +# pragma pack(pop) +#endif + + +/****************************************************************************/ +/* oslDateTime */ +/****************************************************************************/ + +typedef struct _oslDateTime +{ + /*----------------------------------------------------------------------*/ + /** contains the nanoseconds . + */ + sal_uInt32 NanoSeconds; + + /** contains the seconds (0-59). + */ + sal_uInt16 Seconds; + + /*----------------------------------------------------------------------*/ + /** contains the minutes (0-59). + */ + sal_uInt16 Minutes; + + /*----------------------------------------------------------------------*/ + /** contains the hour (0-23). + */ + sal_uInt16 Hours; + + /*----------------------------------------------------------------------*/ + /** is the day of month (1-31). + */ + sal_uInt16 Day; + + /*----------------------------------------------------------------------*/ + /** is the day of week (0-6 , 0 : Sunday). + */ + sal_uInt16 DayOfWeek; + + /*----------------------------------------------------------------------*/ + /** is the month of year (1-12). + */ + sal_uInt16 Month; + + /*----------------------------------------------------------------------*/ + /** is the year. + */ + sal_uInt16 Year; + +} oslDateTime; + + +/** Get the current system time as TimeValue. + @return false if any error occurs. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getSystemTime( + TimeValue* pTimeVal ); + + +/** Get the GMT from a TimeValue and fill a struct oslDateTime + @param[in] pTimeVal TimeValue + @param[out] pDateTime On success it receives a struct oslDateTime + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getDateTimeFromTimeValue( + TimeValue* pTimeVal, oslDateTime* pDateTime ); + + +/** Get the GMT from a oslDateTime and fill a TimeValue + @param[in] pDateTime oslDateTime + @param[out] pTimeVal On success it receives a TimeValue + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getTimeValueFromDateTime( + oslDateTime* pDateTime, TimeValue* pTimeVal ); + + +/** Convert GMT to local time + @param[in] pSystemTimeVal system time to convert + @param[out] pLocalTimeVal On success it receives the local time + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getLocalTimeFromSystemTime( + TimeValue* pSystemTimeVal, TimeValue* pLocalTimeVal ); + + +/** Convert local time to GMT + @param[in] pLocalTimeVal local time to convert + @param[out] pSystemTimeVal On success it receives the system time + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getSystemTimeFromLocalTime( + TimeValue* pLocalTimeVal, TimeValue* pSystemTimeVal ); + + +/** Get the value of the global timer + @return current timer value in milli seconds + */ + +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getGlobalTimer(void); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_TIME_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/util.h b/include/osl/util.h new file mode 100644 index 000000000000..e9afe39ac20f --- /dev/null +++ b/include/osl/util.h @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef _OSL_UTIL_H_ +#define _OSL_UTIL_H_ + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + @param pEthernetAddr 6 bytes of memory + + @return sal_True if the ethernetaddress could be retrieved. <br> + sal_False if no address could be found. This may be either because + there is no ethernet card or there is no appropriate algorithm + implemented on the platform. In this case, pEthernetAddr is + unchanged. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getEthernetAddress( sal_uInt8 *pEthernetAddr ); + +#ifdef __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |