repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
snosov1/opencv | 3rdparty/openexr/Iex/IexThrowErrnoExc.h | <reponame>snosov1/opencv
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXTHROWERRNOEXC_H
#define INCLUDED_IEXTHROWERRNOEXC_H
//----------------------------------------------------------
//
// A function which throws ExcErrno exceptions
//
//----------------------------------------------------------
#include "IexBaseExc.h"
namespace Iex {
//--------------------------------------------------------------------------
//
// Function throwErrnoExc() throws an exception which corresponds to
// error code errnum. The exception text is initialized with a copy
// of the string passed to throwErrnoExc(), where all occurrences of
// "%T" have been replaced with the output of strerror(oserror()).
//
// Example:
//
// If opening file /tmp/output failed with an ENOENT error code,
// calling
//
// throwErrnoExc ();
//
// or
//
// throwErrnoExc ("%T.");
//
// will throw an EnoentExc whose text reads
//
// No such file or directory.
//
// More detailed messages can be assembled using stringstreams:
//
// std::stringstream s;
// s << "Cannot open file " << name << " (%T).";
// throwErrnoExc (s);
//
// The resulting exception contains the following text:
//
// Cannot open file /tmp/output (No such file or directory).
//
// Alternatively, you may want to use the THROW_ERRNO macro defined
// in IexMacros.h:
//
// THROW_ERRNO ("Cannot open file " << name << " (%T).")
//
//--------------------------------------------------------------------------
void throwErrnoExc (const std::string &txt, int errnum);
void throwErrnoExc (const std::string &txt = "%T." /*, int errnum = oserror() */);
} // namespace Iex
#endif
|
snosov1/opencv | 3rdparty/openexr/IlmImf/ImfCheckedArithmetic.h | <reponame>snosov1/opencv
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_CHECKED_ARITHMETIC_H
#define INCLUDED_IMF_CHECKED_ARITHMETIC_H
//-----------------------------------------------------------------------------
//
// Integer arithmetic operations that throw exceptions
// on overflow, underflow or division by zero.
//
//-----------------------------------------------------------------------------
#include <limits>
#include <IexMathExc.h>
namespace Imf {
template <bool b> struct StaticAssertionFailed;
template <> struct StaticAssertionFailed <true> {};
#define IMF_STATIC_ASSERT(x) \
do {StaticAssertionFailed <x> staticAssertionFailed;} while (false)
template <class T>
T
uiMult (T a, T b)
{
//
// Unsigned integer multiplication
//
IMF_STATIC_ASSERT (!std::numeric_limits<T>::is_signed &&
std::numeric_limits<T>::is_integer);
if (a > 0 && b > std::numeric_limits<T>::max() / a)
throw Iex::OverflowExc ("Integer multiplication overflow.");
return a * b;
}
template <class T>
T
uiDiv (T a, T b)
{
//
// Unsigned integer division
//
IMF_STATIC_ASSERT (!std::numeric_limits<T>::is_signed &&
std::numeric_limits<T>::is_integer);
if (b == 0)
throw Iex::DivzeroExc ("Integer division by zero.");
return a / b;
}
template <class T>
T
uiAdd (T a, T b)
{
//
// Unsigned integer addition
//
IMF_STATIC_ASSERT (!std::numeric_limits<T>::is_signed &&
std::numeric_limits<T>::is_integer);
if (a > std::numeric_limits<T>::max() - b)
throw Iex::OverflowExc ("Integer addition overflow.");
return a + b;
}
template <class T>
T
uiSub (T a, T b)
{
//
// Unsigned integer subtraction
//
IMF_STATIC_ASSERT (!std::numeric_limits<T>::is_signed &&
std::numeric_limits<T>::is_integer);
if (a < b)
throw Iex::UnderflowExc ("Integer subtraction underflow.");
return a - b;
}
template <class T>
size_t
checkArraySize (T n, size_t s)
{
//
// Verify that the size, in bytes, of an array with n elements
// of size s can be computed without overflowing:
//
// If computing
//
// size_t (n) * s
//
// would overflow, then throw an Iex::OverflowExc exception.
// Otherwise return
//
// size_t (n).
//
IMF_STATIC_ASSERT (!std::numeric_limits<T>::is_signed &&
std::numeric_limits<T>::is_integer);
IMF_STATIC_ASSERT (sizeof (T) <= sizeof (size_t));
if (size_t (n) > std::numeric_limits<size_t>::max() / s)
throw Iex::OverflowExc ("Integer multiplication overflow.");
return size_t (n);
}
} // namespace Imf
#endif
|
snosov1/opencv | samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/RobustMatcher.h | /*
* RobustMatcher.h
*
* Created on: Jun 4, 2014
* Author: eriba
*/
#ifndef ROBUSTMATCHER_H_
#define ROBUSTMATCHER_H_
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
class RobustMatcher {
public:
RobustMatcher() : ratio_(0.8f)
{
// ORB is the default feature
detector_ = cv::ORB::create();
extractor_ = cv::ORB::create();
// BruteFroce matcher with Norm Hamming is the default matcher
matcher_ = cv::makePtr<cv::BFMatcher>((int)cv::NORM_HAMMING, false);
}
virtual ~RobustMatcher();
// Set the feature detector
void setFeatureDetector(const cv::Ptr<cv::FeatureDetector>& detect) { detector_ = detect; }
// Set the descriptor extractor
void setDescriptorExtractor(const cv::Ptr<cv::DescriptorExtractor>& desc) { extractor_ = desc; }
// Set the matcher
void setDescriptorMatcher(const cv::Ptr<cv::DescriptorMatcher>& match) { matcher_ = match; }
// Compute the keypoints of an image
void computeKeyPoints( const cv::Mat& image, std::vector<cv::KeyPoint>& keypoints);
// Compute the descriptors of an image given its keypoints
void computeDescriptors( const cv::Mat& image, std::vector<cv::KeyPoint>& keypoints, cv::Mat& descriptors);
// Set ratio parameter for the ratio test
void setRatio( float rat) { ratio_ = rat; }
// Clear matches for which NN ratio is > than threshold
// return the number of removed points
// (corresponding entries being cleared,
// i.e. size will be 0)
int ratioTest(std::vector<std::vector<cv::DMatch> > &matches);
// Insert symmetrical matches in symMatches vector
void symmetryTest( const std::vector<std::vector<cv::DMatch> >& matches1,
const std::vector<std::vector<cv::DMatch> >& matches2,
std::vector<cv::DMatch>& symMatches );
// Match feature points using ratio and symmetry test
void robustMatch( const cv::Mat& frame, std::vector<cv::DMatch>& good_matches,
std::vector<cv::KeyPoint>& keypoints_frame,
const cv::Mat& descriptors_model );
// Match feature points using ratio test
void fastRobustMatch( const cv::Mat& frame, std::vector<cv::DMatch>& good_matches,
std::vector<cv::KeyPoint>& keypoints_frame,
const cv::Mat& descriptors_model );
private:
// pointer to the feature point detector object
cv::Ptr<cv::FeatureDetector> detector_;
// pointer to the feature descriptor extractor object
cv::Ptr<cv::DescriptorExtractor> extractor_;
// pointer to the matcher object
cv::Ptr<cv::DescriptorMatcher> matcher_;
// max ratio between 1st and 2nd NN
float ratio_;
};
#endif /* ROBUSTMATCHER_H_ */
|
snosov1/opencv | 3rdparty/openexr/Imath/ImathPlatform.h | <gh_stars>100-1000
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHPLATFORM_H
#define INCLUDED_IMATHPLATFORM_H
//----------------------------------------------------------------------------
//
// ImathPlatform.h
//
// This file contains functions and constants which aren't
// provided by the system libraries, compilers, or includes on
// certain platforms.
//
//----------------------------------------------------------------------------
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923 // pi/2
#endif
//-----------------------------------------------------------------------------
//
// Some, but not all, C++ compilers support the C99 restrict
// keyword or some variant of it, for example, __restrict.
//
//-----------------------------------------------------------------------------
#if defined __GNUC__
//
// supports __restrict
//
#define IMATH_RESTRICT __restrict
#elif defined (__INTEL_COMPILER) || \
defined(__ICL) || \
defined(__ICC) || \
defined(__ECC)
//
// supports restrict
//
#define IMATH_RESTRICT restrict
#elif defined __sgi
//
// supports restrict
//
#define IMATH_RESTRICT restrict
#elif defined _MSC_VER
//
// supports __restrict
//
// #define IMATH_RESTRICT __restrict
#define IMATH_RESTRICT
#else
//
// restrict / __restrict not supported
//
#define IMATH_RESTRICT
#endif
#endif // INCLUDED_IMATHPLATFORM_H
|
snosov1/opencv | samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/Mesh.h | /*
* Mesh.h
*
* Created on: Apr 9, 2014
* Author: edgar
*/
#ifndef MESH_H_
#define MESH_H_
#include <iostream>
#include <opencv2/core/core.hpp>
// --------------------------------------------------- //
// TRIANGLE CLASS //
// --------------------------------------------------- //
class Triangle {
public:
explicit Triangle(int id, cv::Point3f V0, cv::Point3f V1, cv::Point3f V2);
virtual ~Triangle();
cv::Point3f getV0() const { return v0_; }
cv::Point3f getV1() const { return v1_; }
cv::Point3f getV2() const { return v2_; }
private:
/** The identifier number of the triangle */
int id_;
/** The three vertices that defines the triangle */
cv::Point3f v0_, v1_, v2_;
};
// --------------------------------------------------- //
// RAY CLASS //
// --------------------------------------------------- //
class Ray {
public:
explicit Ray(cv::Point3f P0, cv::Point3f P1);
virtual ~Ray();
cv::Point3f getP0() { return p0_; }
cv::Point3f getP1() { return p1_; }
private:
/** The two points that defines the ray */
cv::Point3f p0_, p1_;
};
// --------------------------------------------------- //
// OBJECT MESH CLASS //
// --------------------------------------------------- //
class Mesh
{
public:
Mesh();
virtual ~Mesh();
std::vector<std::vector<int> > getTrianglesList() const { return list_triangles_; }
cv::Point3f getVertex(int pos) const { return list_vertex_[pos]; }
int getNumVertices() const { return num_vertexs_; }
void load(const std::string path_file);
private:
/** The identification number of the mesh */
int id_;
/** The current number of vertices in the mesh */
int num_vertexs_;
/** The current number of triangles in the mesh */
int num_triangles_;
/* The list of triangles of the mesh */
std::vector<cv::Point3f> list_vertex_;
/* The list of triangles of the mesh */
std::vector<std::vector<int> > list_triangles_;
};
#endif /* OBJECTMESH_H_ */
|
snosov1/opencv | 3rdparty/openexr/Iex/IexErrnoExc.h | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXERRNOEXC_H
#define INCLUDED_IEXERRNOEXC_H
//----------------------------------------------------------------
//
// Exceptions which correspond to "errno" error codes.
//
//----------------------------------------------------------------
#include "IexBaseExc.h"
namespace Iex {
DEFINE_EXC (EpermExc, ErrnoExc)
DEFINE_EXC (EnoentExc, ErrnoExc)
DEFINE_EXC (EsrchExc, ErrnoExc)
DEFINE_EXC (EintrExc, ErrnoExc)
DEFINE_EXC (EioExc, ErrnoExc)
DEFINE_EXC (EnxioExc, ErrnoExc)
DEFINE_EXC (E2bigExc, ErrnoExc)
DEFINE_EXC (EnoexecExc, ErrnoExc)
DEFINE_EXC (EbadfExc, ErrnoExc)
DEFINE_EXC (EchildExc, ErrnoExc)
DEFINE_EXC (EagainExc, ErrnoExc)
DEFINE_EXC (EnomemExc, ErrnoExc)
DEFINE_EXC (EaccesExc, ErrnoExc)
DEFINE_EXC (EfaultExc, ErrnoExc)
DEFINE_EXC (EnotblkExc, ErrnoExc)
DEFINE_EXC (EbusyExc, ErrnoExc)
DEFINE_EXC (EexistExc, ErrnoExc)
DEFINE_EXC (ExdevExc, ErrnoExc)
DEFINE_EXC (EnodevExc, ErrnoExc)
DEFINE_EXC (EnotdirExc, ErrnoExc)
DEFINE_EXC (EisdirExc, ErrnoExc)
DEFINE_EXC (EinvalExc, ErrnoExc)
DEFINE_EXC (EnfileExc, ErrnoExc)
DEFINE_EXC (EmfileExc, ErrnoExc)
DEFINE_EXC (EnottyExc, ErrnoExc)
DEFINE_EXC (EtxtbsyExc, ErrnoExc)
DEFINE_EXC (EfbigExc, ErrnoExc)
DEFINE_EXC (EnospcExc, ErrnoExc)
DEFINE_EXC (EspipeExc, ErrnoExc)
DEFINE_EXC (ErofsExc, ErrnoExc)
DEFINE_EXC (EmlinkExc, ErrnoExc)
DEFINE_EXC (EpipeExc, ErrnoExc)
DEFINE_EXC (EdomExc, ErrnoExc)
DEFINE_EXC (ErangeExc, ErrnoExc)
DEFINE_EXC (EnomsgExc, ErrnoExc)
DEFINE_EXC (EidrmExc, ErrnoExc)
DEFINE_EXC (EchrngExc, ErrnoExc)
DEFINE_EXC (El2nsyncExc, ErrnoExc)
DEFINE_EXC (El3hltExc, ErrnoExc)
DEFINE_EXC (El3rstExc, ErrnoExc)
DEFINE_EXC (ElnrngExc, ErrnoExc)
DEFINE_EXC (EunatchExc, ErrnoExc)
DEFINE_EXC (EnocsiExc, ErrnoExc)
DEFINE_EXC (El2hltExc, ErrnoExc)
DEFINE_EXC (EdeadlkExc, ErrnoExc)
DEFINE_EXC (EnolckExc, ErrnoExc)
DEFINE_EXC (EbadeExc, ErrnoExc)
DEFINE_EXC (EbadrExc, ErrnoExc)
DEFINE_EXC (ExfullExc, ErrnoExc)
DEFINE_EXC (EnoanoExc, ErrnoExc)
DEFINE_EXC (EbadrqcExc, ErrnoExc)
DEFINE_EXC (EbadsltExc, ErrnoExc)
DEFINE_EXC (EdeadlockExc, ErrnoExc)
DEFINE_EXC (EbfontExc, ErrnoExc)
DEFINE_EXC (EnostrExc, ErrnoExc)
DEFINE_EXC (EnodataExc, ErrnoExc)
DEFINE_EXC (EtimeExc, ErrnoExc)
DEFINE_EXC (EnosrExc, ErrnoExc)
DEFINE_EXC (EnonetExc, ErrnoExc)
DEFINE_EXC (EnopkgExc, ErrnoExc)
DEFINE_EXC (EremoteExc, ErrnoExc)
DEFINE_EXC (EnolinkExc, ErrnoExc)
DEFINE_EXC (EadvExc, ErrnoExc)
DEFINE_EXC (EsrmntExc, ErrnoExc)
DEFINE_EXC (EcommExc, ErrnoExc)
DEFINE_EXC (EprotoExc, ErrnoExc)
DEFINE_EXC (EmultihopExc, ErrnoExc)
DEFINE_EXC (EbadmsgExc, ErrnoExc)
DEFINE_EXC (EnametoolongExc, ErrnoExc)
DEFINE_EXC (EoverflowExc, ErrnoExc)
DEFINE_EXC (EnotuniqExc, ErrnoExc)
DEFINE_EXC (EbadfdExc, ErrnoExc)
DEFINE_EXC (EremchgExc, ErrnoExc)
DEFINE_EXC (ElibaccExc, ErrnoExc)
DEFINE_EXC (ElibbadExc, ErrnoExc)
DEFINE_EXC (ElibscnExc, ErrnoExc)
DEFINE_EXC (ElibmaxExc, ErrnoExc)
DEFINE_EXC (ElibexecExc, ErrnoExc)
DEFINE_EXC (EilseqExc, ErrnoExc)
DEFINE_EXC (EnosysExc, ErrnoExc)
DEFINE_EXC (EloopExc, ErrnoExc)
DEFINE_EXC (ErestartExc, ErrnoExc)
DEFINE_EXC (EstrpipeExc, ErrnoExc)
DEFINE_EXC (EnotemptyExc, ErrnoExc)
DEFINE_EXC (EusersExc, ErrnoExc)
DEFINE_EXC (EnotsockExc, ErrnoExc)
DEFINE_EXC (EdestaddrreqExc, ErrnoExc)
DEFINE_EXC (EmsgsizeExc, ErrnoExc)
DEFINE_EXC (EprototypeExc, ErrnoExc)
DEFINE_EXC (EnoprotooptExc, ErrnoExc)
DEFINE_EXC (EprotonosupportExc, ErrnoExc)
DEFINE_EXC (EsocktnosupportExc, ErrnoExc)
DEFINE_EXC (EopnotsuppExc, ErrnoExc)
DEFINE_EXC (EpfnosupportExc, ErrnoExc)
DEFINE_EXC (EafnosupportExc, ErrnoExc)
DEFINE_EXC (EaddrinuseExc, ErrnoExc)
DEFINE_EXC (EaddrnotavailExc, ErrnoExc)
DEFINE_EXC (EnetdownExc, ErrnoExc)
DEFINE_EXC (EnetunreachExc, ErrnoExc)
DEFINE_EXC (EnetresetExc, ErrnoExc)
DEFINE_EXC (EconnabortedExc, ErrnoExc)
DEFINE_EXC (EconnresetExc, ErrnoExc)
DEFINE_EXC (EnobufsExc, ErrnoExc)
DEFINE_EXC (EisconnExc, ErrnoExc)
DEFINE_EXC (EnotconnExc, ErrnoExc)
DEFINE_EXC (EshutdownExc, ErrnoExc)
DEFINE_EXC (EtoomanyrefsExc, ErrnoExc)
DEFINE_EXC (EtimedoutExc, ErrnoExc)
DEFINE_EXC (EconnrefusedExc, ErrnoExc)
DEFINE_EXC (EhostdownExc, ErrnoExc)
DEFINE_EXC (EhostunreachExc, ErrnoExc)
DEFINE_EXC (EalreadyExc, ErrnoExc)
DEFINE_EXC (EinprogressExc, ErrnoExc)
DEFINE_EXC (EstaleExc, ErrnoExc)
DEFINE_EXC (EioresidExc, ErrnoExc)
DEFINE_EXC (EucleanExc, ErrnoExc)
DEFINE_EXC (EnotnamExc, ErrnoExc)
DEFINE_EXC (EnavailExc, ErrnoExc)
DEFINE_EXC (EisnamExc, ErrnoExc)
DEFINE_EXC (EremoteioExc, ErrnoExc)
DEFINE_EXC (EinitExc, ErrnoExc)
DEFINE_EXC (EremdevExc, ErrnoExc)
DEFINE_EXC (EcanceledExc, ErrnoExc)
DEFINE_EXC (EnolimfileExc, ErrnoExc)
DEFINE_EXC (EproclimExc, ErrnoExc)
DEFINE_EXC (EdisjointExc, ErrnoExc)
DEFINE_EXC (EnologinExc, ErrnoExc)
DEFINE_EXC (EloginlimExc, ErrnoExc)
DEFINE_EXC (EgrouploopExc, ErrnoExc)
DEFINE_EXC (EnoattachExc, ErrnoExc)
DEFINE_EXC (EnotsupExc, ErrnoExc)
DEFINE_EXC (EnoattrExc, ErrnoExc)
DEFINE_EXC (EdircorruptedExc, ErrnoExc)
DEFINE_EXC (EdquotExc, ErrnoExc)
DEFINE_EXC (EnfsremoteExc, ErrnoExc)
DEFINE_EXC (EcontrollerExc, ErrnoExc)
DEFINE_EXC (EnotcontrollerExc, ErrnoExc)
DEFINE_EXC (EenqueuedExc, ErrnoExc)
DEFINE_EXC (EnotenqueuedExc, ErrnoExc)
DEFINE_EXC (EjoinedExc, ErrnoExc)
DEFINE_EXC (EnotjoinedExc, ErrnoExc)
DEFINE_EXC (EnoprocExc, ErrnoExc)
DEFINE_EXC (EmustrunExc, ErrnoExc)
DEFINE_EXC (EnotstoppedExc, ErrnoExc)
DEFINE_EXC (EclockcpuExc, ErrnoExc)
DEFINE_EXC (EinvalstateExc, ErrnoExc)
DEFINE_EXC (EnoexistExc, ErrnoExc)
DEFINE_EXC (EendofminorExc, ErrnoExc)
DEFINE_EXC (EbufsizeExc, ErrnoExc)
DEFINE_EXC (EemptyExc, ErrnoExc)
DEFINE_EXC (EnointrgroupExc, ErrnoExc)
DEFINE_EXC (EinvalmodeExc, ErrnoExc)
DEFINE_EXC (EcantextentExc, ErrnoExc)
DEFINE_EXC (EinvaltimeExc, ErrnoExc)
DEFINE_EXC (EdestroyedExc, ErrnoExc)
} // namespace Iex
#endif
|
snosov1/opencv | 3rdparty/openexr/Imath/ImathSphere.h | <reponame>snosov1/opencv
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHSPHERE_H
#define INCLUDED_IMATHSPHERE_H
//-------------------------------------
//
// A 3D sphere class template
//
//-------------------------------------
#include "ImathVec.h"
#include "ImathBox.h"
#include "ImathLine.h"
namespace Imath {
template <class T>
class Sphere3
{
public:
Vec3<T> center;
T radius;
//---------------
// Constructors
//---------------
Sphere3() : center(0,0,0), radius(0) {}
Sphere3(const Vec3<T> &c, T r) : center(c), radius(r) {}
//-------------------------------------------------------------------
// Utilities:
//
// s.circumscribe(b) sets center and radius of sphere s
// so that the s tightly encloses box b.
//
// s.intersectT (l, t) If sphere s and line l intersect, then
// intersectT() computes the smallest t,
// t >= 0, so that l(t) is a point on the
// sphere. intersectT() then returns true.
//
// If s and l do not intersect, intersectT()
// returns false.
//
// s.intersect (l, i) If sphere s and line l intersect, then
// intersect() calls s.intersectT(l,t) and
// computes i = l(t).
//
// If s and l do not intersect, intersect()
// returns false.
//
//-------------------------------------------------------------------
void circumscribe(const Box<Vec3<T> > &box);
bool intersect(const Line3<T> &l, Vec3<T> &intersection) const;
bool intersectT(const Line3<T> &l, T &t) const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Sphere3<float> Sphere3f;
typedef Sphere3<double> Sphere3d;
//---------------
// Implementation
//---------------
template <class T>
void Sphere3<T>::circumscribe(const Box<Vec3<T> > &box)
{
center = T(0.5) * (box.min + box.max);
radius = (box.max - center).length();
}
template <class T>
bool Sphere3<T>::intersectT(const Line3<T> &line, T &t) const
{
bool doesIntersect = true;
Vec3<T> v = line.pos - center;
T B = T(2.0) * (line.dir ^ v);
T C = (v ^ v) - (radius * radius);
// compute discriminant
// if negative, there is no intersection
T discr = B*B - T(4.0)*C;
if (discr < 0.0)
{
// line and Sphere3 do not intersect
doesIntersect = false;
}
else
{
// t0: (-B - sqrt(B^2 - 4AC)) / 2A (A = 1)
T sqroot = Math<T>::sqrt(discr);
t = (-B - sqroot) * T(0.5);
if (t < 0.0)
{
// no intersection, try t1: (-B + sqrt(B^2 - 4AC)) / 2A (A = 1)
t = (-B + sqroot) * T(0.5);
}
if (t < 0.0)
doesIntersect = false;
}
return doesIntersect;
}
template <class T>
bool Sphere3<T>::intersect(const Line3<T> &line, Vec3<T> &intersection) const
{
T t;
if (intersectT (line, t))
{
intersection = line(t);
return true;
}
else
{
return false;
}
}
} //namespace Imath
#endif
|
snosov1/opencv | 3rdparty/libwebp/utils/bit_writer.h | // Copyright 2011 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Bit writing and boolean coder
//
// Author: Skal (<EMAIL>)
#ifndef WEBP_UTILS_BIT_WRITER_H_
#define WEBP_UTILS_BIT_WRITER_H_
#include "../webp/types.h"
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
//------------------------------------------------------------------------------
// Bit-writing
typedef struct VP8BitWriter VP8BitWriter;
struct VP8BitWriter {
int32_t range_; // range-1
int32_t value_;
int run_; // number of outstanding bits
int nb_bits_; // number of pending bits
uint8_t* buf_; // internal buffer. Re-allocated regularly. Not owned.
size_t pos_;
size_t max_pos_;
int error_; // true in case of error
};
// Initialize the object. Allocates some initial memory based on expected_size.
int VP8BitWriterInit(VP8BitWriter* const bw, size_t expected_size);
// Finalize the bitstream coding. Returns a pointer to the internal buffer.
uint8_t* VP8BitWriterFinish(VP8BitWriter* const bw);
// Release any pending memory and zeroes the object. Not a mandatory call.
// Only useful in case of error, when the internal buffer hasn't been grabbed!
void VP8BitWriterWipeOut(VP8BitWriter* const bw);
int VP8PutBit(VP8BitWriter* const bw, int bit, int prob);
int VP8PutBitUniform(VP8BitWriter* const bw, int bit);
void VP8PutValue(VP8BitWriter* const bw, int value, int nb_bits);
void VP8PutSignedValue(VP8BitWriter* const bw, int value, int nb_bits);
// Appends some bytes to the internal buffer. Data is copied.
int VP8BitWriterAppend(VP8BitWriter* const bw,
const uint8_t* data, size_t size);
// return approximate write position (in bits)
static WEBP_INLINE uint64_t VP8BitWriterPos(const VP8BitWriter* const bw) {
return (uint64_t)(bw->pos_ + bw->run_) * 8 + 8 + bw->nb_bits_;
}
// Returns a pointer to the internal buffer.
static WEBP_INLINE uint8_t* VP8BitWriterBuf(const VP8BitWriter* const bw) {
return bw->buf_;
}
// Returns the size of the internal buffer.
static WEBP_INLINE size_t VP8BitWriterSize(const VP8BitWriter* const bw) {
return bw->pos_;
}
//------------------------------------------------------------------------------
// VP8LBitWriter
// TODO(vikasa): VP8LBitWriter is copied as-is from lossless code. There's scope
// of re-using VP8BitWriter. Will evaluate once basic lossless encoder is
// implemented.
typedef struct {
uint8_t* buf_;
size_t bit_pos_;
size_t max_bytes_;
// After all bits are written, the caller must observe the state of
// error_. A value of 1 indicates that a memory allocation failure
// has happened during bit writing. A value of 0 indicates successful
// writing of bits.
int error_;
} VP8LBitWriter;
static WEBP_INLINE size_t VP8LBitWriterNumBytes(VP8LBitWriter* const bw) {
return (bw->bit_pos_ + 7) >> 3;
}
static WEBP_INLINE uint8_t* VP8LBitWriterFinish(VP8LBitWriter* const bw) {
return bw->buf_;
}
// Returns 0 in case of memory allocation error.
int VP8LBitWriterInit(VP8LBitWriter* const bw, size_t expected_size);
void VP8LBitWriterDestroy(VP8LBitWriter* const bw);
// This function writes bits into bytes in increasing addresses, and within
// a byte least-significant-bit first.
//
// The function can write up to 16 bits in one go with WriteBits
// Example: let's assume that 3 bits (Rs below) have been written already:
//
// BYTE-0 BYTE+1 BYTE+2
//
// 0000 0RRR 0000 0000 0000 0000
//
// Now, we could write 5 or less bits in MSB by just sifting by 3
// and OR'ing to BYTE-0.
//
// For n bits, we take the last 5 bytes, OR that with high bits in BYTE-0,
// and locate the rest in BYTE+1 and BYTE+2.
//
// VP8LBitWriter's error_ flag is set in case of memory allocation error.
void VP8LWriteBits(VP8LBitWriter* const bw, int n_bits, uint32_t bits);
//------------------------------------------------------------------------------
#if defined(__cplusplus) || defined(c_plusplus)
} // extern "C"
#endif
#endif /* WEBP_UTILS_BIT_WRITER_H_ */
|
snosov1/opencv | 3rdparty/libtiff/uvcode.h | <reponame>snosov1/opencv
/* Version 1.0 generated April 7, 1997 by <NAME>, SGI */
#define UV_SQSIZ (float)0.003500
#define UV_NDIVS 16289
#define UV_VSTART (float)0.016940
#define UV_NVS 163
static struct {
float ustart;
short nus, ncum;
} uv_row[UV_NVS] = {
{ (float)0.247663, 4, 0 },
{ (float)0.243779, 6, 4 },
{ (float)0.241684, 7, 10 },
{ (float)0.237874, 9, 17 },
{ (float)0.235906, 10, 26 },
{ (float)0.232153, 12, 36 },
{ (float)0.228352, 14, 48 },
{ (float)0.226259, 15, 62 },
{ (float)0.222371, 17, 77 },
{ (float)0.220410, 18, 94 },
{ (float)0.214710, 21, 112 },
{ (float)0.212714, 22, 133 },
{ (float)0.210721, 23, 155 },
{ (float)0.204976, 26, 178 },
{ (float)0.202986, 27, 204 },
{ (float)0.199245, 29, 231 },
{ (float)0.195525, 31, 260 },
{ (float)0.193560, 32, 291 },
{ (float)0.189878, 34, 323 },
{ (float)0.186216, 36, 357 },
{ (float)0.186216, 36, 393 },
{ (float)0.182592, 38, 429 },
{ (float)0.179003, 40, 467 },
{ (float)0.175466, 42, 507 },
{ (float)0.172001, 44, 549 },
{ (float)0.172001, 44, 593 },
{ (float)0.168612, 46, 637 },
{ (float)0.168612, 46, 683 },
{ (float)0.163575, 49, 729 },
{ (float)0.158642, 52, 778 },
{ (float)0.158642, 52, 830 },
{ (float)0.158642, 52, 882 },
{ (float)0.153815, 55, 934 },
{ (float)0.153815, 55, 989 },
{ (float)0.149097, 58, 1044 },
{ (float)0.149097, 58, 1102 },
{ (float)0.142746, 62, 1160 },
{ (float)0.142746, 62, 1222 },
{ (float)0.142746, 62, 1284 },
{ (float)0.138270, 65, 1346 },
{ (float)0.138270, 65, 1411 },
{ (float)0.138270, 65, 1476 },
{ (float)0.132166, 69, 1541 },
{ (float)0.132166, 69, 1610 },
{ (float)0.126204, 73, 1679 },
{ (float)0.126204, 73, 1752 },
{ (float)0.126204, 73, 1825 },
{ (float)0.120381, 77, 1898 },
{ (float)0.120381, 77, 1975 },
{ (float)0.120381, 77, 2052 },
{ (float)0.120381, 77, 2129 },
{ (float)0.112962, 82, 2206 },
{ (float)0.112962, 82, 2288 },
{ (float)0.112962, 82, 2370 },
{ (float)0.107450, 86, 2452 },
{ (float)0.107450, 86, 2538 },
{ (float)0.107450, 86, 2624 },
{ (float)0.107450, 86, 2710 },
{ (float)0.100343, 91, 2796 },
{ (float)0.100343, 91, 2887 },
{ (float)0.100343, 91, 2978 },
{ (float)0.095126, 95, 3069 },
{ (float)0.095126, 95, 3164 },
{ (float)0.095126, 95, 3259 },
{ (float)0.095126, 95, 3354 },
{ (float)0.088276, 100, 3449 },
{ (float)0.088276, 100, 3549 },
{ (float)0.088276, 100, 3649 },
{ (float)0.088276, 100, 3749 },
{ (float)0.081523, 105, 3849 },
{ (float)0.081523, 105, 3954 },
{ (float)0.081523, 105, 4059 },
{ (float)0.081523, 105, 4164 },
{ (float)0.074861, 110, 4269 },
{ (float)0.074861, 110, 4379 },
{ (float)0.074861, 110, 4489 },
{ (float)0.074861, 110, 4599 },
{ (float)0.068290, 115, 4709 },
{ (float)0.068290, 115, 4824 },
{ (float)0.068290, 115, 4939 },
{ (float)0.068290, 115, 5054 },
{ (float)0.063573, 119, 5169 },
{ (float)0.063573, 119, 5288 },
{ (float)0.063573, 119, 5407 },
{ (float)0.063573, 119, 5526 },
{ (float)0.057219, 124, 5645 },
{ (float)0.057219, 124, 5769 },
{ (float)0.057219, 124, 5893 },
{ (float)0.057219, 124, 6017 },
{ (float)0.050985, 129, 6141 },
{ (float)0.050985, 129, 6270 },
{ (float)0.050985, 129, 6399 },
{ (float)0.050985, 129, 6528 },
{ (float)0.050985, 129, 6657 },
{ (float)0.044859, 134, 6786 },
{ (float)0.044859, 134, 6920 },
{ (float)0.044859, 134, 7054 },
{ (float)0.044859, 134, 7188 },
{ (float)0.040571, 138, 7322 },
{ (float)0.040571, 138, 7460 },
{ (float)0.040571, 138, 7598 },
{ (float)0.040571, 138, 7736 },
{ (float)0.036339, 142, 7874 },
{ (float)0.036339, 142, 8016 },
{ (float)0.036339, 142, 8158 },
{ (float)0.036339, 142, 8300 },
{ (float)0.032139, 146, 8442 },
{ (float)0.032139, 146, 8588 },
{ (float)0.032139, 146, 8734 },
{ (float)0.032139, 146, 8880 },
{ (float)0.027947, 150, 9026 },
{ (float)0.027947, 150, 9176 },
{ (float)0.027947, 150, 9326 },
{ (float)0.023739, 154, 9476 },
{ (float)0.023739, 154, 9630 },
{ (float)0.023739, 154, 9784 },
{ (float)0.023739, 154, 9938 },
{ (float)0.019504, 158, 10092 },
{ (float)0.019504, 158, 10250 },
{ (float)0.019504, 158, 10408 },
{ (float)0.016976, 161, 10566 },
{ (float)0.016976, 161, 10727 },
{ (float)0.016976, 161, 10888 },
{ (float)0.016976, 161, 11049 },
{ (float)0.012639, 165, 11210 },
{ (float)0.012639, 165, 11375 },
{ (float)0.012639, 165, 11540 },
{ (float)0.009991, 168, 11705 },
{ (float)0.009991, 168, 11873 },
{ (float)0.009991, 168, 12041 },
{ (float)0.009016, 170, 12209 },
{ (float)0.009016, 170, 12379 },
{ (float)0.009016, 170, 12549 },
{ (float)0.006217, 173, 12719 },
{ (float)0.006217, 173, 12892 },
{ (float)0.005097, 175, 13065 },
{ (float)0.005097, 175, 13240 },
{ (float)0.005097, 175, 13415 },
{ (float)0.003909, 177, 13590 },
{ (float)0.003909, 177, 13767 },
{ (float)0.002340, 177, 13944 },
{ (float)0.002389, 170, 14121 },
{ (float)0.001068, 164, 14291 },
{ (float)0.001653, 157, 14455 },
{ (float)0.000717, 150, 14612 },
{ (float)0.001614, 143, 14762 },
{ (float)0.000270, 136, 14905 },
{ (float)0.000484, 129, 15041 },
{ (float)0.001103, 123, 15170 },
{ (float)0.001242, 115, 15293 },
{ (float)0.001188, 109, 15408 },
{ (float)0.001011, 103, 15517 },
{ (float)0.000709, 97, 15620 },
{ (float)0.000301, 89, 15717 },
{ (float)0.002416, 82, 15806 },
{ (float)0.003251, 76, 15888 },
{ (float)0.003246, 69, 15964 },
{ (float)0.004141, 62, 16033 },
{ (float)0.005963, 55, 16095 },
{ (float)0.008839, 47, 16150 },
{ (float)0.010490, 40, 16197 },
{ (float)0.016994, 31, 16237 },
{ (float)0.023659, 21, 16268 },
};
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
|
Booritas/slideio | src/slideio/drivers/scn/scnstruct.h | <reponame>Booritas/slideio
#pragma once
#include <map>
#include "slideio/imagetools/tifftools.hpp"
struct SCNDimensionInfo
{
int width;
int height;
int r;
int c;
int ifd;
};
struct SCNTilingInfo
{
std::map<int, const slideio::TiffDirectory*> channel2ifd;
};
|
kmcallister/rip | regclobber.c | // Run a program while clearing registers after every instruction,
// except those before the symbol FORBID_REGS.
//
// Build: gcc -O2 -Wall -o regclobber regclobber.c
// Run: ./regclobber prog args...
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/reg.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#define ERRNO_DIE(_msg) \
do { perror((_msg)); exit(1); } while (0)
#define CHECK(_call) \
do { if ((_call) < 0) ERRNO_DIE(#_call); } while (0)
uint64_t inst_count = 0, clobber_count = 0;
__attribute__((noreturn))
void finish(int retval) {
fprintf(stderr, "\nExecuted %lu instructions; clobbered registers %lu times.\n",
inst_count, clobber_count);
exit(retval);
}
// Allow register access below this address, so that the child
// can make system calls.
uint64_t regs_boundary = 0;
// Set regs_boundary from the FORBID_REGS symbol in the child.
void find_regs_boundary(pid_t child) {
char *cmd;
CHECK(asprintf(&cmd, "nm /proc/%ld/exe | grep 'FORBID_REGS$'", (long) child));
FILE *symbols = popen(cmd, "r");
if (symbols == NULL)
ERRNO_DIE("popen");
if (fscanf(symbols, "%lx", ®s_boundary) < 1) {
fprintf(stderr, "WARNING: Could not find symbol FORBID_REGS.\n"
"Registers are forbidden everywhere.\n");
}
CHECK(pclose(symbols));
free(cmd);
}
// Bits to preserve in EFLAGS. Everything but the condition codes.
#define EFLAGS_MASK 0xfffffffffffff32a
// Clobber forbidden registers in the traced process.
void clobber_regs(pid_t child) {
struct user_regs_struct regs_int;
struct user_fpregs_struct regs_fp;
CHECK(ptrace(PTRACE_GETREGS, child, 0, ®s_int));
if (regs_int.rip < regs_boundary)
return;
CHECK(ptrace(PTRACE_GETFPREGS, child, 0, ®s_fp));
// Clear everything before the instruction pointer,
// plus the stack pointer and some bits of EFLAGS.
// See /usr/include/sys/user.h for the layout of
// this struct.
memset(®s_int, 0, offsetof(struct user_regs_struct, rip));
regs_int.rsp = 0;
regs_int.eflags &= EFLAGS_MASK;
// Clear x87 and SSE registers.
memset(regs_fp.st_space, 0, sizeof(regs_fp.st_space));
memset(regs_fp.xmm_space, 0, sizeof(regs_fp.xmm_space));
CHECK(ptrace(PTRACE_SETREGS, child, 0, ®s_int));
CHECK(ptrace(PTRACE_SETFPREGS, child, 0, ®s_fp));
clobber_count++;
}
volatile sig_atomic_t exit_sig = 0;
void handle_exit_sig(int signum) {
exit_sig = signum;
}
int main(int argc, char *argv[]) {
int i;
if (argc < 2) {
fprintf(stderr, "Usage: %s prog args...\n", argv[0]);
return 1;
}
// Fork and exec the target program.
pid_t child;
CHECK(child = fork());
if (!child) {
CHECK(ptrace(PTRACE_TRACEME));
CHECK(raise(SIGSTOP));
execvp(argv[1], argv+1);
ERRNO_DIE("execvp");
}
// Call finish() if the user presses ^C.
CHECK(signal(SIGINT, handle_exit_sig));
// Wait for attach.
int status;
CHECK(waitpid(child, &status, 0));
// Let the child execute into and out of execvp().
for (i=0; i<2; i++) {
CHECK(ptrace(PTRACE_SYSCALL, child, 0, 0));
CHECK(waitpid(child, &status, 0));
}
// Look for the FORBID_REGS symbol.
find_regs_boundary(child);
// Single-step the program and clobber registers.
while (!exit_sig) {
// For this demo it's simpler if we don't deliver signals to
// the child, so the last argument to ptrace() is zero.
CHECK(ptrace(PTRACE_SINGLESTEP, child, 0, 0));
CHECK(waitpid(child, &status, 0));
if (WIFEXITED(status))
finish(WEXITSTATUS(status));
inst_count++;
clobber_regs(child);
}
finish(128 + exit_sig);
}
|
mstewartgallus/linted | include/lntd/sched.h | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_SCHED_H
#define LNTD_SCHED_H
#include "lntd/error.h"
/**
* @file
*
* Task scheduling.
*/
struct lntd_async_pool;
struct lntd_async_task;
union lntd_async_ck;
typedef int lntd_sched_priority;
struct lntd_async_pool;
struct lntd_async_task;
struct lntd_sched_task_idle;
struct lntd_sched_task_sleep_until;
struct timespec;
lntd_error lntd_sched_getpriority(lntd_sched_priority *priorityp);
lntd_error lntd_sched_time(struct timespec *data);
lntd_error
lntd_sched_task_idle_create(struct lntd_sched_task_idle **taskp,
void *data);
void lntd_sched_task_idle_destroy(struct lntd_sched_task_idle *task);
void *lntd_sched_task_idle_data(struct lntd_sched_task_idle *task);
void lntd_sched_task_idle_cancel(struct lntd_sched_task_idle *task);
void lntd_sched_task_idle_submit(struct lntd_async_pool *pool,
struct lntd_sched_task_idle *task,
union lntd_async_ck task_ck,
void *userstate);
lntd_error lntd_sched_task_sleep_until_create(
struct lntd_sched_task_sleep_until **taskp, void *data);
void lntd_sched_task_sleep_until_destroy(
struct lntd_sched_task_sleep_until *task);
void lntd_sched_task_sleep_until_submit(
struct lntd_async_pool *pool,
struct lntd_sched_task_sleep_until *task,
union lntd_async_ck task_ck, void *userstate,
struct timespec const *req);
void lntd_sched_task_sleep_until_time(
struct lntd_sched_task_sleep_until *task, struct timespec *time);
void *lntd_sched_task_sleep_until_data(
struct lntd_sched_task_sleep_until *task);
void lntd_sched_task_sleep_until_cancel(
struct lntd_sched_task_sleep_until *task);
void lntd_sched_do_idle(struct lntd_async_pool *pool,
struct lntd_async_task *task);
void lntd_sched_do_sleep_until(struct lntd_async_pool *pool,
struct lntd_async_task *task);
static inline void lntd_sched_light_yield(void);
#if defined __i386__ || defined __amd64__
static inline void lntd_sched_light_yield(void)
{
__asm__ __volatile__("pause");
}
#elif defined __arm__ || defined __aarch64__
static inline void lntd_sched_light_yield(void)
{
__asm__ __volatile__("yield");
}
#elif defined __powerpc__
static inline void lntd_sched_light_yield(void)
{
/* Do nothing */
}
#endif
#endif /* LNTD_SCHED_H */
|
mstewartgallus/linted | src/stack/stack.c | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#include "lntd/stack.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/node.h"
#include "lntd/sched.h"
#include "lntd/trigger.h"
#include <errno.h>
#include <stdatomic.h>
#include <stdint.h>
typedef _Atomic(struct lntd_node *) atomic_node;
struct lntd_stack {
atomic_node inbox;
struct lntd_trigger inbox_filled;
char __padding[64U - sizeof(struct lntd_trigger) % 64U];
struct lntd_node *outbox;
};
static inline void refresh_node(struct lntd_node *node)
{
node->next = 0;
}
lntd_error lntd_stack_create(struct lntd_stack **stackp)
{
lntd_error err = 0;
struct lntd_stack *stack;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *stack);
if (err != 0)
return err;
stack = xx;
}
atomic_node ptr = ATOMIC_VAR_INIT((void *)0);
stack->inbox = ptr;
stack->outbox = 0;
lntd_trigger_create(&stack->inbox_filled, 0);
*stackp = stack;
return 0;
}
void lntd_stack_destroy(struct lntd_stack *stack)
{
lntd_trigger_destroy(&stack->inbox_filled);
lntd_mem_free(stack);
}
void lntd_stack_send(struct lntd_stack *stack, struct lntd_node *node)
{
for (;;) {
struct lntd_node *next = atomic_load_explicit(
&stack->inbox, memory_order_relaxed);
node->next = next;
atomic_thread_fence(memory_order_release);
if (atomic_compare_exchange_weak_explicit(
&stack->inbox, &next, node,
memory_order_relaxed, memory_order_relaxed)) {
break;
}
lntd_sched_light_yield();
}
lntd_trigger_set(&stack->inbox_filled);
}
void lntd_stack_recv(struct lntd_stack *stack, struct lntd_node **nodep)
{
struct lntd_node *ret = atomic_exchange_explicit(
&stack->inbox, 0, memory_order_relaxed);
if (ret != 0)
goto put_on_outbox;
ret = stack->outbox;
if (ret != 0) {
stack->outbox = ret->next;
goto give_node;
}
for (;;) {
for (uint_fast8_t ii = 0U; ii < 20U; ++ii) {
ret = atomic_exchange_explicit(
&stack->inbox, 0, memory_order_relaxed);
if (ret != 0)
goto put_on_outbox;
lntd_sched_light_yield();
}
lntd_trigger_wait(&stack->inbox_filled);
}
put_on_outbox:
atomic_thread_fence(memory_order_acquire);
struct lntd_node *start = ret->next;
if (start != 0) {
struct lntd_node *end = start;
for (;;) {
struct lntd_node *next = end->next;
if (0 == next)
break;
end = next;
}
end->next = stack->outbox;
stack->outbox = start;
}
give_node:
refresh_node(ret);
*nodep = ret;
}
lntd_error lntd_stack_try_recv(struct lntd_stack *stack,
struct lntd_node **nodep)
{
struct lntd_node *ret = atomic_exchange_explicit(
&stack->inbox, 0, memory_order_relaxed);
if (ret != 0)
goto put_on_outbox;
ret = stack->outbox;
if (ret != 0) {
stack->outbox = ret->next;
goto give_node;
}
return EAGAIN;
put_on_outbox:
atomic_thread_fence(memory_order_acquire);
struct lntd_node *start = ret->next;
if (start != 0) {
struct lntd_node *end = start;
for (;;) {
struct lntd_node *next = end->next;
if (0 == next)
break;
end = next;
}
end->next = stack->outbox;
stack->outbox = start;
}
give_node:
refresh_node(ret);
*nodep = ret;
return 0;
}
|
mstewartgallus/linted | include/lntd/locale.h | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_LOCALE_H
#define LNTD_LOCALE_H
#include "lntd/error.h"
#include "lntd/ko.h"
/**
* @file
*
* Abstracts over various localizations of common text.
*/
lntd_error lntd_locale_on_bad_option(lntd_ko ko,
char const *process_name,
char const *bad_option);
lntd_error lntd_locale_try_for_more_help(lntd_ko ko,
char const *process_name,
char const *help_option);
lntd_error lntd_locale_version(lntd_ko ko, char const *package_string,
char const *copyright_year);
#endif /* LNTD_LOCALE_H */
|
mstewartgallus/linted | src/ko/ko-windows.c | <filename>src/ko/ko-windows.c
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0600
#include "config.h"
#include "lntd/ko.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/str.h"
#include "lntd/utf.h"
#include "lntd/util.h"
#include <direct.h>
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <windows.h>
#include <winsock2.h>
lntd_error lntd_ko_open(lntd_ko *kop, lntd_ko dirko,
char const *pathname, unsigned long flags)
{
lntd_error err;
if ((flags & ~LNTD_KO_RDONLY & ~LNTD_KO_WRONLY & ~LNTD_KO_RDWR &
~LNTD_KO_APPEND & ~LNTD_KO_SYNC & ~LNTD_KO_DIRECTORY) !=
0U)
return LNTD_ERROR_INVALID_PARAMETER;
bool ko_rdonly = (flags & LNTD_KO_RDONLY) != 0U;
bool ko_wronly = (flags & LNTD_KO_WRONLY) != 0U;
bool ko_rdwr = (flags & LNTD_KO_RDWR) != 0U;
bool ko_append = (flags & LNTD_KO_APPEND) != 0U;
bool ko_sync = (flags & LNTD_KO_SYNC) != 0U;
bool ko_directory = (flags & LNTD_KO_DIRECTORY) != 0U;
if (ko_rdonly && ko_wronly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_rdwr && ko_rdonly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_rdwr && ko_wronly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_append && !ko_wronly)
return LNTD_ERROR_INVALID_PARAMETER;
if ((ko_directory && ko_rdonly) ||
(ko_directory && ko_wronly) || (ko_directory && ko_rdwr) ||
(ko_directory && ko_sync))
return LNTD_ERROR_INVALID_PARAMETER;
DWORD desired_access = 0;
if (ko_rdonly)
desired_access |= GENERIC_READ;
if (ko_wronly)
desired_access |= GENERIC_WRITE;
if (ko_rdwr)
desired_access |= GENERIC_READ | GENERIC_WRITE;
char *real_path;
{
char *xx;
err = lntd_ko_real_path(&xx, dirko, pathname);
if (err != 0)
return err;
real_path = xx;
}
wchar_t *pathname_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(real_path, &xx);
if (err != 0)
goto free_real_path;
pathname_utf2 = xx;
}
lntd_ko ko = CreateFile(pathname_utf2, desired_access, 0, 0,
OPEN_EXISTING, 0, 0);
if (INVALID_HANDLE_VALUE == ko) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
}
lntd_mem_free(pathname_utf2);
free_real_path:
lntd_mem_free(real_path);
if (err != 0)
return err;
*kop = ko;
return 0;
}
lntd_error lntd_ko_close(lntd_ko ko)
{
lntd_error err;
if (SOCKET_ERROR == closesocket((uintptr_t)ko)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
if (err != WSAENOTSOCK)
return err;
}
if (!CloseHandle(ko)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
lntd_ko lntd_ko__get_stdin(void)
{
return (lntd_ko)GetStdHandle(STD_INPUT_HANDLE);
}
lntd_ko lntd_ko__get_stdout(void)
{
return (lntd_ko)GetStdHandle(STD_OUTPUT_HANDLE);
}
lntd_ko lntd_ko__get_stderr(void)
{
return (lntd_ko)GetStdHandle(STD_ERROR_HANDLE);
}
lntd_error lntd_ko_change_directory(char const *pathname)
{
lntd_error err = 0;
wchar_t *pathname_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(pathname, &xx);
if (err != 0)
return err;
pathname_utf2 = xx;
}
if (!SetCurrentDirectoryW(pathname_utf2)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
}
lntd_mem_free(pathname_utf2);
return err;
}
lntd_error lntd_ko_symlink(char const *oldpath, char const *newpath)
{
lntd_error err = 0;
wchar_t *oldpath_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(oldpath, &xx);
if (err != 0)
return err;
oldpath_utf2 = xx;
}
wchar_t *newpath_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(newpath, &xx);
if (err != 0)
goto free_oldpath;
newpath_utf2 = xx;
}
if (!CreateSymbolicLinkW(newpath_utf2, oldpath_utf2,
SYMBOLIC_LINK_FLAG_DIRECTORY)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
}
lntd_mem_free(newpath_utf2);
free_oldpath:
lntd_mem_free(oldpath_utf2);
return err;
}
/**
* @bug Windows NT: work on directories other than `LNTD_KO_CWD`
* @bug Windows NT: actually resolve the path
*/
lntd_error lntd_ko_real_path(char **resultp, lntd_ko dirko,
char const *pathname)
{
lntd_error err = 0;
LNTD_ASSERT(resultp != 0);
LNTD_ASSERT(pathname != 0);
if (dirko != LNTD_KO_CWD)
return LNTD_ERROR_INVALID_PARAMETER;
char *result;
{
char *xx;
err = lntd_str_dup(&xx, pathname);
if (err != 0)
return err;
result = xx;
}
*resultp = result;
return 0;
}
|
mstewartgallus/linted | include/lntd/error.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ERROR_H
#define LNTD_ERROR_H
#if defined HAVE_WINDOWS_API
#include "error-windows.h"
#elif defined HAVE_POSIX_API
#include "error-posix.h"
#else
#error no error code method for this platform has been implemented
#endif
/**
* @file
*
* Abstracts over the system's basic error type.
*/
char const *lntd_error_string(lntd_error err);
void lntd_error_string_free(char const *str);
#endif /* LNTD_ERROR_H */
|
mstewartgallus/linted | src/xcb/xcb.c | <filename>src/xcb/xcb.c
/*
* Copyright 2014 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#include "lntd/xcb.h"
#include "lntd/error.h"
#include "lntd/util.h"
#include <errno.h>
#include <xcb/xcb.h>
#define Success 0
#define BadRequest 1
#define BadValue 2
#define BadWindow 3
#define BadPixmap 4
#define BadAtom 5
#define BadCursor 6
#define BadFont 7
#define BadMatch 8
#define BadDrawable 9
#define BadAccess 10
#define BadAlloc 11
#define BadColor 12
#define BadGC 13
#define BadIDChoice 14
#define BadName 15
#define BadLength 16
#define BadImplementation 17
lntd_error lntd_xcb_conn_error(xcb_connection_t *connection)
{
switch (xcb_connection_has_error(connection)) {
case 0:
return 0;
case XCB_CONN_ERROR:
return EPROTO;
case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
return LNTD_ERROR_UNIMPLEMENTED;
case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
return LNTD_ERROR_OUT_OF_MEMORY;
case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
return LNTD_ERROR_INVALID_PARAMETER;
case XCB_CONN_CLOSED_PARSE_ERR:
return LNTD_ERROR_INVALID_PARAMETER;
default:
LNTD_ASSUME_UNREACHABLE();
}
}
lntd_error lntd_xcb_error(xcb_generic_error_t *error)
{
switch (error->error_code) {
case Success:
return 0;
case BadRequest:
case BadValue:
case BadWindow:
case BadPixmap:
case BadAtom:
case BadCursor:
case BadFont:
case BadMatch:
case BadDrawable:
case BadColor:
case BadGC:
case BadIDChoice:
case BadName:
case BadLength:
return LNTD_ERROR_INVALID_PARAMETER;
case BadAccess:
return LNTD_ERROR_PERMISSION;
case BadAlloc:
return LNTD_ERROR_OUT_OF_MEMORY;
case BadImplementation:
return LNTD_ERROR_UNIMPLEMENTED;
default:
return LNTD_ERROR_UNIMPLEMENTED;
}
}
|
mstewartgallus/linted | docs/todo.h | /* Copyright (C) 2013, 2014, 2015 <NAME>
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty provided
* the copyright notice and this notice are preserved.
*/
/**
*
* @file
*
* Linted -- TODO
*
* @todo Add platform specific information and defines to static
* analysis tooling.
*
* @todo Eventually reduce `-Wstack-usage` to 500.
*
* @todo Port to --host=x86_64-w64-mingw32
*
* @todo Make the process monitor distinguish between transient faults
* and persistent faults.
*
* @todo Use length annotated strings instead of C strings.
*
* @todo Create a notification method.
* Currently, outside administrators can create requests to the
* monitor system but there needs to be a way for the monitor to
* generate notifications. User Mode Linux has the same problem
* and we should learn from how they solve it.
*
* @todo Harden bind mounts with extra flags:
* Possible mount flags:
* - `MS_RDONLY`
* - `MS_NOSUID`
* - `MS_NODEV`
* - `MS_NOEXEC`
* - `MS_SYNCHRONOUS`
* - `MS_REMOUNT`
* - `MS_MANDLOCK`
* - `MS_DIRSYNC`
* - `MS_NOATIME`
* - `MS_NODIRATIME`
* - `MS_BIND`
* - `MS_MOVE`
* - `MS_REC`
* - `MS_SILENT`
* - `MS_POSIXACL`
* - `MS_UNBINDABLE`
* - `MS_PRIVATE`
* - `MS_SLAVE`
* - `MS_SHARED`
* - `MS_RELATIME`
* - `MS_KERNMOUNT`
* - `MS_I_VERSION`
* - `MS_STRICTATIME`
* - `MS_ACTIVE`
* - `MS_NOUSER`
* Mount flags that work on remounts (binds only allow you to
* remount flags):
* - `MS_RDONLY`
* - `MS_SYNCHRONOUS`
* - `MS_MANDLOCK`
* - `MS_I_VERSION`
*
* @todo Check child processes for hangups with a watchdog timer
*
* @todo Create a feed of possible vulnerabilities in all dependencies
*
* @todo Achieve deterministic builds.
* The Dwarf Directory Table can be sort of solved with the option
* `-fdebug-prefix-map` but that still leaves the problem of
* system include files.
*/
|
mstewartgallus/linted | src/ko/ko-test.c | <gh_stars>0
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/start.h"
#include "lntd/test.h"
#include <stddef.h>
#include <stdlib.h>
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-ko-test", 0};
static unsigned char lntd_start_main(char const *const process_name,
size_t argc,
char const *const argv[])
{
lntd_error err;
lntd_ko root;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "/",
LNTD_KO_DIRECTORY);
/* Can happen on Windows NT */
if (LNTD_ERROR_PERMISSION == err)
return EXIT_SUCCESS;
if (err != 0)
LNTD_TEST_FAILURE("err == %s\n",
lntd_error_string(err));
root = xx;
}
err = lntd_ko_close(root);
if (err != 0)
LNTD_TEST_FAILURE("err == %s\n",
lntd_error_string(err));
return EXIT_SUCCESS;
}
|
mstewartgallus/linted | docs/tools.h | <reponame>mstewartgallus/linted<gh_stars>0
/* Copyright (C) 2014, 2015 <NAME>
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty provided
* the copyright notice and this notice are preserved.
/
/**
@file
Linted -- Tools
@section potential Potential tools
<ul>
<li> [Ada
SPARK](http://libre.adacore.com/libre/tools/spark-gpl-edition/) </li>
<li> [Daikon](http://plse.cs.washington.edu/daikon/) </li>
<li> [AFL](http://lcamtuf.coredump.cx/afl/) </li>
<li> [BOON "Buffer Overrun
detectiON"](http://www.cs.berkeley.edu/~daw/boon/) </li>
<li> [Cqual](http://www.cs.umd.edu/~jfoster/cqual/) </li>
<li> [ImProve](https://github.com/tomahawkins/improve/wiki/ImProve)
</li>
<li> [Infer](http://fbinfer.com/) </li>
<li> [joern](https://github.com/fabsx00/joern) </li>
<li> [KLEE](https://klee.github.io/) </li>
<li> [Oink](http://daniel-wilkerson.appspot.com/oink/index.html)
</li>
<li> [Overture Tool](http://overturetool.org/) </li>
<li> [RTL-check](http://rtlcheck.sourceforge.net/) </li>
<li> [Saturn](http://saturn.stanford.edu/) </li>
<li> [S-Spider](https://code.google.com/p/s-spider/) </li>
<li> [Stanse](http://stanse.fi.muni.cz/) </li>
<li>
[TLA+](http://research.microsoft.com/en-us/um/people/lamport/tla/tla.html)
</li>
<li> [OWASP's Dependency
Check](https://bintray.com/jeremy-long/owasp/dependency-check) </li>
<li> [unifdef](http://dotat.at/prog/unifdef/) </li>
<li> [Why3](http://why3.lri.fr/) </li>
<li> [Vera++](https://bitbucket.org/verateam/vera/wiki/Home) </li>
<li> [Yasca](http://sourceforge.net/projects/yasca/) </li>
</ul>
@section useful Useful tools
<ul>
<li> [FlameGraph](https://github.com/brendangregg/FlameGraph)
- Visualizes perf output nicely.
</li>
<li> [Clang-Format](http://clang.llvm.org/)
As of version 3.5:
- Formats code nicely
</li>
li> [Git](http://git-scm.com//)
A version control system
Note that you can sign commits with the `user.signingkey` and
`commit.gpgsign` options.
</li>
</ul>
@subsection instrumenters Instrumenters
<ul>
<li> [GDB](https://www.gnu.org/software/gdb/)
See http://tromey.com/blog/?p=734 for how to set up multiprocess
debugging.
<code>
(gdb) set detach-on-fork off
(gdb) set target-async on
(gdb) set non-stop on
(gdb) set pagination off
</code>
</li>
<li> GLibc Memory Allocator Debug Environment Variables
They are `MALLOC_CHECK_` and `MALLOC_PERTURB_`.
</li>
li> [Apitrace](https://github.com/apitrace/apitrace)
Traces, error checks, replays and profiles OpenGL code.
As of commit a3e4614c7fb0a6ffa8c748bf5d49b34612c9d6d4:
- It works great but before using one needs to set the drawer
process to not use a custom mount space and to change into an
owned directory.
- Can't profile OpenGL ES code well.
- Probably best used by setting the ExecStart in the drawer service
like:
<code>
ExecStart=/usr/bin/env
ExecStart=LD_PRELOAD=/home/sstewartgallus/root/usr/local/stow/apitrace/lib/x86_64-linux-gnu/apitrace/wrappers/egltrace.so
ExecStart="${LINTED_DRAWER}" "window" "window-notifier-drawer" "updater"
</code>
</li>
<li> [Linux Perf
Utils](https://git.kernel.org/cgit/linux/kernel/git/namhyung/linux-perf.git/)
Profiles code performance using CPU counters.
- It works great without any changes and handles multiple processes
well.
- It does not handle a few internal functions in some libraries,
probably due to:
https://bugzilla.kernel.org/show_bug.cgi?id=80671
- In order for perf to handle Mesa's JITted GPU code (from llvmpipe
enabled with LIBGL_ALWAYS_SOFTWARE=true) perf needs Mesa to be
built with PROFILE defined and Mesa needs to output a file
"/tmp/perf-[pid]" mapping symbols to JITted code. This means that
/tmp needs to be available inside the drawer process sandbox and
the drawer can't be trapped in a new process hierarchy with
CLONE_NEWPID. Also Mesa tests the PERF_BUILDID_DIR environment
variable set by perf before writing the file.
- Make sure to download all debug symbols
</li>
<li> [xtrace](http://xtrace.alioth.debian.org//)
As of version 1.3.1:
- Works perfectly for what it does.
- Is kind of useless.
- Doesn't support a -D detach option like strace.
- Doesn't distinguish between multiple open connections well.
- It'd be awesome if it supported features like fault injection as
well ("Maximum number of clients reached" for example.)
</li>
<li> [Valgrind](http://valgrind.org/)
A runtime instrumentor that checks code for errors.
As of version 3.11:
- You have to make sure every running service has a /tmp directory.
- You have to set the pipe prefix appropriately
- You have to set the Valgrind to trace children
- You have to use the latest version from SVN (version 11) to
handle system calls like pivot_root.
- It's a bit buggy with sandboxing but works fine.
- memcheck works fine.
- helgrind can't cope with asynchronous cancellation well.
- All together something like `valgrind --vgdb-prefix=/tmp/vgdb
--trace-children=yes ./scripts/test` works.
</li>
<li> [Address
Sanitizer](http://clang.llvm.org/docs/AddressSanitizer.html)
A compiler debug mode that checks code for errors.
- It works great without any changes.
</li>
</ul>
@subsection analyzers Analyzers
<ul>
<li> [Cppcheck](http://cppcheck.sourceforge.net/)
A code linter.
- It's okay but mostly just catches bad style.
</li>
<li>
[IWYU](https://github.com/include-what-you-use/include-what-you-use/)
Is a bit buggy.
Use like: `make CC='iwyu -I/usr/lib/clang/3.6/include' -k | tee
iwyu.log`
</li>
<li> [CBMC](http://www.cprover.org/cbmc/)
As of version 4.9:
A code simulator that checks for errors.
- It's a bit fiddly to setup but works okay.
- It is particularly annoying that it doesn't know that all indices
into `argv` less than `argc` and greater than or equal to zero
are valid C strings.
- Theoretically it should be able to handle nondeterminism and
concurrency but only if I add a bunch of annotations manually.
</li>
<li> [CPAchecker](http://cpachecker.sosy-lab.org/)
As of version 1.4:
You can't pass flags into the builtin preprocessor such as include
flags.
</li>
<li> [Frama-C](http://frama-c.com/)
As of version Neon-20140301:
- It's a bit fiddly to get working.
- It doesn't work with the system's standard library headers and
supplies its own but it only has a very limited standard library.
- It can't handle concurrency or function pointers in some cases.
</li>
</ul>
@section rejected Rejected Tools
<ul>
<li> [Sparse](http://git.kernel.org/cgit/devel/sparse/sparse.git)
- Works moderately well but isn't particularly better than other
static analyzers without custom annotations.
- Doesn't allow specifying system base dirs other than GCC's and
doesn't properly recognize the `-isystem` flag.
- Segfaults on some code.
- I'm unsure about the license of it.
</li>
<li> [Divine](http://divine.fi.muni.cz/manual.html#installation)
- It does not compile properly.
</li>
<li> [MOPS](http://web.cs.ucdavis.edu/~hchen/mops/)
- It does not compile properly.
</li>
<li> [VOGL](https://github.com/ValveSoftware/vogl)
- It doesn't support EGL. See the issue at
https://github.com/ValveSoftware/vogl/issues/193
</li>
<li> [Eclipse's CODAN and builtin
analyzers](http://wiki.eclipse.org/CDT/designs/StaticAnalysis)
- Projects can be easily imported into Eclipse via the Autotools
project import tool.
- I haven't investigated if there is a way to get CODAN to work in
a command line style and not only from the Eclipse GUI.
- Most of CODANs analyzers are very dumb.
- Eclipse seems to be analyzing even unused source files such as
are used for different platforms builds which error out.
- A unified analyzer framework might make it easier to plugin
multiple static analyzers in the future.
</li>
<li> [GLSL-Debugger](https://glsl-debugger.github.io/)
- I couldn't get it to build as it required Qt4.
</li>
<li> [Build EAR](https://github.com/rizsotto/Bear)
- It works perfectly except each time it is rerun it overwrites the
previous compile_commands.json and doesn't take into account the
old commands.
</li>
<li> [Linux Dwarves
tools](https://git.kernel.org/cgit/devel/pahole/pahole.git/)
A set of simple binary analysis tools.
- codiff Diffs changes in binaries
- dtagnames Lists tag names
- pahole Finds holes in structures
- pdwtags Dwarf information pretty printer
- pfunct Displays information about functions
- pglobal Displays information about global variables
- prefcnt Tries to find unreferenced tags
As of version 1.9:
- These tools would be extremely useful if they worked on a wider
range of types. So far, they all seem to break and not handle any
structure types that aren't extremely ordinary.
</li>
<li> [Clang's -Wthread-safety
flag](http://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
As of version 3.5:
- This tool is okay but cannot handle thread cancellation which is
needed to kill worker threads that are taking too long. Luckily,
we don't use thread cancellation anymore.
- Also it doesn't work with C well. See the bug at
http://llvm.org/bugs/show_bug.cgi?id=20403.
</li>
<li> [Smatch](http://smatch.sourceforge.net/)
As of version 0.4.1:
- Does not handle shared object linking (which makes sense as it
was developed for the Linux kernel primarily.)
- Doesn't integrate with the hosts toolchain so it doesn't have
important headers such as stddef.h.
- Lots of false positives, the tool seems to misunderstand a lot of
standard C that the Linux kernel doesn't use.
</li>
<li> [SPLINT](http://www.splint.org/)
As of version 3.12:
- Does not know about standard defines such as `UINT32_MAX`.
- Only seems to be able parse traditional style C code which
declares all variables up front.
</li>
<li> Flawfinder or RATS
- Seems to be defunct right now.
- Gives many false positives.
- Did give a nice tip about how `InitializeCriticalSection` can
throw an exception however. Note that this only applies to
Windows XP and lower.
</li>
li> [sixgill](http://sixgill.org/)
- This fails compiling due to the use of `-Werror` in the build
scripts and sixgill deleting an abstract object with a non-virtual
destructor.
</li>
@section also See Also
- http://gulliver.eu.org/program_dev_check_environments
- https://www.gnu.org/software/hurd/open_issues/code_analysis.html
- NIST's Software Assurance Metrics and Tool Evaluation (SAMATE)
project.
- The Open Source Quality Project at Berkeley.
*/
|
mstewartgallus/linted | src/async/async-posix.c | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/async.h"
#include "lntd/channel.h"
#include "lntd/error.h"
#include "lntd/io.h"
#include "lntd/ko-stack.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/node.h"
#include "lntd/proc.h"
#include "lntd/sched.h"
#include "lntd/signal.h"
#include "lntd/stack.h"
#include "lntd/util.h"
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>
#define UPCAST(X) ((void *)(X))
#define DOWNCAST(T, X) ((T *)(X))
#if defined _POSIX_SPIN_LOCKS
typedef pthread_spinlock_t spinlock;
#else
typedef pthread_mutex_t spinlock;
#endif
static inline void spinlock_init(spinlock *lock);
static inline lntd_error spinlock_lock(spinlock *lock);
static inline lntd_error spinlock_unlock(spinlock *lock);
static size_t small_stack_size(void);
/**
* A one reader to many writers queue. Should be able to retrieve
* many values at once. As all writes are a direct result of
* submitted commands there is no need to worry about it growing
* too large.
*/
struct completion_queue;
static lntd_error
completion_queue_create(struct completion_queue **queuep);
static void complete_task(struct completion_queue *queue,
struct lntd_async_task *task);
static lntd_error completion_recv(struct completion_queue *queue,
struct lntd_async_task **taskp);
static lntd_error completion_try_recv(struct completion_queue *queue,
struct lntd_async_task **taskp);
static void completion_queue_destroy(struct completion_queue *queue);
struct job_queue;
static lntd_error job_queue_create(struct job_queue **queuep);
static void job_submit(struct job_queue *queue,
struct lntd_async_task *task);
static lntd_error job_recv(struct job_queue *queue,
struct lntd_async_task **taskp);
static void job_queue_destroy(struct job_queue *queue);
struct worker_queue;
static lntd_error worker_queue_create(struct worker_queue **queuep);
static lntd_error worker_try_submit(struct worker_queue *queue,
struct lntd_async_task *task);
static lntd_error worker_recv(struct worker_queue *queue,
struct lntd_async_task **taskp);
static void worker_queue_destroy(struct worker_queue *queue);
struct waiter_queue;
static lntd_error waiter_queue_create(struct waiter_queue **queuep);
static void waiter_queue_destroy(struct waiter_queue *queue);
static lntd_ko waiter_ko(struct waiter_queue *queue);
static void waiter_submit(struct waiter_queue *queue,
struct lntd_async_waiter *waiter);
static lntd_error waiter_try_recv(struct waiter_queue *queue,
struct lntd_async_waiter **waiterp);
struct worker_pool;
static lntd_error worker_pool_create(struct worker_pool **poolp,
struct job_queue *job_queue,
struct lntd_async_pool *pool,
unsigned max_tasks);
static void worker_pool_destroy(struct worker_pool *pool);
struct wait_manager;
static lntd_error wait_manager_create(struct wait_manager **managerp,
struct waiter_queue *waiter_queue,
struct lntd_async_pool *pool,
unsigned max_pollers);
static void wait_manager_destroy(struct wait_manager *manager);
struct canceller;
static void canceller_init(struct canceller *canceller);
static void canceller_start(struct canceller *canceller);
static void canceller_stop(struct canceller *canceller);
static void canceller_cancel(struct canceller *canceller);
static bool canceller_check_or_register(struct canceller *canceller,
pthread_t self);
static bool canceller_check_and_unregister(struct canceller *canceller);
struct canceller {
pthread_t owner;
spinlock lock;
bool cancelled : 1U;
bool cancel_reply : 1U;
bool owned : 1U;
bool in_flight : 1U;
};
struct lntd_async_pool {
struct wait_manager *wait_manager;
struct worker_pool *worker_pool;
struct job_queue *job_queue;
struct waiter_queue *waiter_queue;
struct completion_queue *completion_queue;
};
struct lntd_async_task {
struct lntd_node parent;
struct canceller canceller;
lntd_error err;
bool thread_canceller : 1U;
char __padding1[64U -
(sizeof(struct lntd_node) +
sizeof(struct canceller) + sizeof(lntd_error) +
sizeof(bool)) %
64U];
/* Stuff below should only be written by one thread on the fast
* path */
void *data;
void *userstate;
union lntd_async_ck task_ck;
lntd_async_type type;
};
struct lntd_async_waiter {
struct lntd_node parent;
short revents;
bool thread_canceller : 1U;
char
__padding1[64U -
(sizeof(struct lntd_node) + sizeof(bool)) % 64U];
/* Stuff below should only be written by one thread on the fast
* path */
struct lntd_async_task *task;
lntd_ko ko;
short flags;
};
lntd_error lntd_async_pool_create(struct lntd_async_pool **poolp,
unsigned max_tasks)
{
LNTD_ASSERT_NOT_NULL(poolp);
lntd_error err;
struct lntd_async_pool *pool;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *pool);
if (err != 0)
return err;
pool = xx;
}
struct waiter_queue *waiter_queue;
{
struct waiter_queue *xx;
err = waiter_queue_create(&xx);
if (err != 0)
goto free_pool;
waiter_queue = xx;
}
struct job_queue *job_queue;
{
struct job_queue *xx;
err = job_queue_create(&xx);
if (err != 0)
goto destroy_waiter_queue;
job_queue = xx;
}
struct completion_queue *completion_queue;
{
struct completion_queue *xx;
err = completion_queue_create(&xx);
if (err != 0)
goto destroy_job_queue;
completion_queue = xx;
}
struct wait_manager *wait_manager;
{
struct wait_manager *xx;
err = wait_manager_create(&xx, waiter_queue, pool,
max_tasks);
if (err != 0)
goto destroy_completion_queue;
wait_manager = xx;
}
struct worker_pool *worker_pool;
{
struct worker_pool *xx;
err =
worker_pool_create(&xx, job_queue, pool, max_tasks);
if (err != 0)
goto destroy_wait_manager;
worker_pool = xx;
}
pool->worker_pool = worker_pool;
pool->wait_manager = wait_manager;
pool->waiter_queue = waiter_queue;
pool->job_queue = job_queue;
pool->completion_queue = completion_queue;
*poolp = pool;
return 0;
destroy_wait_manager:
wait_manager_destroy(wait_manager);
destroy_completion_queue:
completion_queue_destroy(completion_queue);
destroy_job_queue:
job_queue_destroy(job_queue);
destroy_waiter_queue:
waiter_queue_destroy(waiter_queue);
free_pool:
lntd_mem_free(pool);
LNTD_ASSERT(err != 0);
return err;
}
lntd_error lntd_async_pool_destroy(struct lntd_async_pool *pool)
{
LNTD_ASSERT_NOT_NULL(pool);
struct wait_manager *wait_manager = pool->wait_manager;
struct worker_pool *worker_pool = pool->worker_pool;
struct job_queue *job_queue = pool->job_queue;
struct waiter_queue *waiter_queue = pool->waiter_queue;
struct completion_queue *completion_queue =
pool->completion_queue;
worker_pool_destroy(worker_pool);
wait_manager_destroy(wait_manager);
job_queue_destroy(job_queue);
waiter_queue_destroy(waiter_queue);
completion_queue_destroy(completion_queue);
lntd_mem_free(pool);
return 0;
}
void lntd_async_pool_resubmit(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
LNTD_ASSERT_NOT_NULL(pool);
LNTD_ASSERT_NOT_NULL(task);
if (canceller_check_and_unregister(&task->canceller)) {
task->err = LNTD_ERROR_CANCELLED;
complete_task(pool->completion_queue, task);
return;
}
job_submit(pool->job_queue, task);
}
void lntd_async_pool_complete(struct lntd_async_pool *pool,
struct lntd_async_task *task,
lntd_error task_err)
{
LNTD_ASSERT_NOT_NULL(pool);
LNTD_ASSERT_NOT_NULL(task);
canceller_stop(&task->canceller);
task->err = task_err;
complete_task(pool->completion_queue, task);
}
void lntd_async_pool_wait_on_poll(struct lntd_async_pool *pool,
struct lntd_async_waiter *waiter,
struct lntd_async_task *task,
lntd_ko ko, short flags)
{
LNTD_ASSERT_NOT_NULL(pool);
LNTD_ASSERT_NOT_NULL(waiter);
LNTD_ASSERT_NOT_NULL(task);
if (canceller_check_and_unregister(&task->canceller)) {
task->err = LNTD_ERROR_CANCELLED;
complete_task(pool->completion_queue, task);
return;
}
waiter->task = task;
waiter->ko = ko;
waiter->flags = flags;
waiter_submit(pool->waiter_queue, waiter);
}
lntd_error lntd_async_pool_wait(struct lntd_async_pool *pool,
struct lntd_async_result *resultp)
{
lntd_error err = 0;
struct completion_queue *queue = pool->completion_queue;
struct lntd_async_task *task;
{
struct lntd_async_task *xx;
err = completion_recv(queue, &xx);
if (err != 0)
return err;
task = xx;
}
resultp->task_ck = task->task_ck;
resultp->err = task->err;
resultp->userstate = task->userstate;
return 0;
}
lntd_error lntd_async_pool_poll(struct lntd_async_pool *pool,
struct lntd_async_result *resultp)
{
LNTD_ASSERT_NOT_NULL(pool);
lntd_error err = 0;
struct completion_queue *queue = pool->completion_queue;
struct lntd_async_task *task;
{
struct lntd_async_task *xx;
err = completion_try_recv(queue, &xx);
if (err != 0)
return err;
task = xx;
}
resultp->task_ck = task->task_ck;
resultp->err = task->err;
resultp->userstate = task->userstate;
return 0;
}
lntd_error lntd_async_waiter_create(struct lntd_async_waiter **waiterp)
{
LNTD_ASSERT_NOT_NULL(waiterp);
lntd_error err;
struct lntd_async_waiter *waiter;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *waiter);
if (err != 0)
return err;
waiter = xx;
}
waiter->revents = 0;
waiter->thread_canceller = false;
*waiterp = waiter;
return 0;
}
void lntd_async_waiter_destroy(struct lntd_async_waiter *waiter)
{
lntd_mem_free(waiter);
}
short lntd_async_waiter_revents(struct lntd_async_waiter *waiter)
{
LNTD_ASSERT_NOT_NULL(waiter);
short ev = waiter->revents;
waiter->revents = 0;
return ev;
}
lntd_error lntd_async_task_create(struct lntd_async_task **taskp,
void *data, lntd_async_type type)
{
LNTD_ASSERT_NOT_NULL(taskp);
lntd_error err;
struct lntd_async_task *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
canceller_init(&task->canceller);
task->data = data;
task->type = type;
task->err = LNTD_ERROR_INVALID_PARAMETER;
task->thread_canceller = false;
*taskp = task;
return 0;
}
void lntd_async_task_destroy(struct lntd_async_task *task)
{
lntd_mem_free(task);
}
void lntd_async_task_cancel(struct lntd_async_task *task)
{
LNTD_ASSERT_NOT_NULL(task);
canceller_cancel(&task->canceller);
}
void lntd_async_task_submit(struct lntd_async_pool *pool,
struct lntd_async_task *task,
union lntd_async_ck task_ck,
void *userstate)
{
LNTD_ASSERT_NOT_NULL(task);
task->task_ck = task_ck;
task->userstate = userstate;
LNTD_ASSERT_NOT_NULL(pool);
LNTD_ASSERT_NOT_NULL(task);
canceller_start(&task->canceller);
job_submit(pool->job_queue, task);
}
void *lntd_async_task_data(struct lntd_async_task *task)
{
LNTD_ASSERT_NOT_NULL(task);
return task->data;
}
static void *master_worker_routine(void *arg);
static void *worker_routine(void *arg);
static void run_task(struct lntd_async_pool *pool,
struct lntd_async_task *task);
struct worker_pool;
struct worker {
struct lntd_async_pool *pool;
struct worker_queue *queue;
pthread_t thread;
};
struct worker_pool {
struct lntd_async_pool *async_pool;
struct job_queue *job_queue;
struct worker_queue **worker_queues;
size_t worker_stacks_size;
void *worker_stacks;
size_t worker_count;
pthread_t master_thread;
struct worker workers[];
};
static lntd_error worker_pool_create(struct worker_pool **poolp,
struct job_queue *job_queue,
struct lntd_async_pool *async_pool,
unsigned max_tasks)
{
LNTD_ASSERT_NOT_NULL(poolp);
LNTD_ASSERT_NOT_NULL(job_queue);
LNTD_ASSERT_NOT_NULL(async_pool);
lntd_error err = 0;
size_t workers_count = max_tasks;
struct worker_pool *pool;
size_t workers_size = workers_count * sizeof pool->workers[0U];
size_t worker_pool_size = sizeof *pool + workers_size;
LNTD_ASSERT(worker_pool_size > 0U);
{
void *xx;
err = lntd_mem_alloc(&xx, worker_pool_size);
if (err != 0)
return err;
pool = xx;
}
size_t queues_created = 0U;
for (; queues_created < max_tasks; ++queues_created) {
struct worker_queue **queuep =
&pool->workers[queues_created].queue;
err = worker_queue_create(queuep);
if (err != 0)
goto destroy_worker_queues;
}
size_t stack_size = small_stack_size();
long maybe_page_size = sysconf(_SC_PAGE_SIZE);
LNTD_ASSERT(maybe_page_size >= 0);
size_t page_size = maybe_page_size;
size_t stack_and_guard_size = stack_size + page_size;
size_t worker_stacks_size =
page_size + stack_and_guard_size * workers_count;
void *worker_stacks = mmap(
0, worker_stacks_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_GROWSDOWN | MAP_STACK, -1,
0);
if (0 == worker_stacks) {
err = errno;
LNTD_ASSUME(err != 0);
goto destroy_worker_queues;
}
/* Guard pages are shared between the stacks */
if (-1 ==
mprotect((char *)worker_stacks, page_size, PROT_NONE)) {
err = errno;
LNTD_ASSUME(err != 0);
goto destroy_stacks;
}
char *tail_guard_page =
(char *)worker_stacks + page_size + stack_size;
for (size_t ii = 0U; ii < workers_count; ++ii) {
if (-1 ==
mprotect(tail_guard_page, page_size, PROT_NONE)) {
err = errno;
LNTD_ASSUME(err != 0);
goto destroy_stacks;
}
tail_guard_page += page_size + stack_size;
}
pool->worker_count = workers_count;
pool->worker_stacks = worker_stacks;
pool->worker_stacks_size = worker_stacks_size;
pool->job_queue = job_queue;
pool->async_pool = async_pool;
size_t created_threads = 0U;
{
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if (err != 0)
goto destroy_stacks;
char *last_stack = (char *)worker_stacks + page_size;
for (; created_threads < max_tasks; ++created_threads) {
err = pthread_attr_setstack(&attr, last_stack,
stack_size);
if (err != 0) {
LNTD_ASSERT(
err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(false);
}
last_stack += stack_size + page_size;
struct worker *worker =
&pool->workers[created_threads];
worker->pool = async_pool;
/* Get EPIPEs */
/* SIGPIPE may not be blocked already */
sigset_t oldset;
{
sigset_t pipe_set;
sigemptyset(&pipe_set);
sigaddset(&pipe_set, SIGPIPE);
err = pthread_sigmask(
SIG_BLOCK, &pipe_set, &oldset);
if (err != 0)
break;
}
err = pthread_create(&worker->thread, &attr,
worker_routine, worker);
lntd_error mask_err =
pthread_sigmask(SIG_SETMASK, &oldset, 0);
if (0 == err)
err = mask_err;
if (err != 0)
break;
}
lntd_error destroy_err = pthread_attr_destroy(&attr);
if (0 == err)
err = destroy_err;
}
if (err != 0)
goto destroy_threads;
err = pthread_create(&pool->master_thread, 0,
master_worker_routine, pool);
if (err != 0)
goto destroy_threads;
*poolp = pool;
return 0;
destroy_threads:
for (size_t ii = 0U; ii < created_threads; ++ii) {
struct worker const *worker = &pool->workers[ii];
struct worker_queue *worker_queue = worker->queue;
pthread_t thread = worker->thread;
for (;;) {
struct lntd_async_task task;
task.thread_canceller = true;
lntd_error try_err =
worker_try_submit(worker_queue, &task);
if (0 == try_err) {
pthread_join(thread, 0);
break;
}
lntd_error kill_err =
pthread_kill(thread, LNTD_ASYNCH_SIGNO);
if (kill_err != 0 && kill_err != EAGAIN) {
LNTD_ASSERT(kill_err != ESRCH);
LNTD_ASSERT(
kill_err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(false);
}
sched_yield();
}
}
destroy_stacks:
munmap(worker_stacks, worker_stacks_size);
destroy_worker_queues:
for (size_t ii = 0U; ii < queues_created; ++ii)
worker_queue_destroy(pool->workers[ii].queue);
lntd_mem_free(pool);
return err;
}
static void worker_pool_destroy(struct worker_pool *pool)
{
LNTD_ASSERT_NOT_NULL(pool);
struct job_queue *job_queue = pool->job_queue;
pthread_t master_thread = pool->master_thread;
struct worker const *workers = pool->workers;
size_t worker_count = pool->worker_count;
{
struct lntd_async_task task;
task.thread_canceller = true;
job_submit(job_queue, &task);
pthread_join(master_thread, 0);
}
munmap(pool->worker_stacks, pool->worker_stacks_size);
for (size_t ii = 0U; ii < worker_count; ++ii)
worker_queue_destroy(workers[ii].queue);
lntd_mem_free(pool);
}
static void *master_worker_routine(void *arg)
{
LNTD_ASSERT_NOT_NULL(arg);
lntd_proc_name("async-worker-master");
struct worker_pool *pool = arg;
struct job_queue *job_queue = pool->job_queue;
struct worker const *workers = pool->workers;
size_t max_tasks = pool->worker_count;
for (;;) {
struct lntd_async_task *task;
{
struct lntd_async_task *xx;
job_recv(job_queue, &xx);
task = xx;
}
if (task->thread_canceller)
break;
for (;;) {
for (size_t ii = 0U; ii < max_tasks; ++ii) {
lntd_error err = worker_try_submit(
workers[ii].queue, task);
if (LNTD_ERROR_AGAIN == err)
continue;
if (0 == err)
goto exit_loop;
}
sched_yield();
}
exit_loop:
;
}
for (size_t ii = 0U; ii < max_tasks; ++ii) {
struct worker *worker = &pool->workers[ii];
struct worker_queue *worker_queue = worker->queue;
pthread_t thread = worker->thread;
for (;;) {
struct lntd_async_task task;
task.thread_canceller = true;
lntd_error err =
worker_try_submit(worker_queue, &task);
if (0 == err) {
pthread_join(thread, 0);
break;
}
err = pthread_kill(thread, LNTD_ASYNCH_SIGNO);
if (err != 0 && err != EAGAIN) {
LNTD_ASSERT(err != ESRCH);
LNTD_ASSERT(
err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(false);
}
sched_yield();
}
}
return 0;
}
static void *worker_routine(void *arg)
{
LNTD_ASSERT_NOT_NULL(arg);
lntd_proc_name("async-worker");
struct worker *worker = arg;
struct lntd_async_pool *async_pool = worker->pool;
struct worker_queue *worker_queue = worker->queue;
pthread_t self = pthread_self();
for (;;) {
struct lntd_async_task *task;
{
struct lntd_async_task *xx;
worker_recv(worker_queue, &xx);
task = xx;
}
if (task->thread_canceller)
break;
if (canceller_check_or_register(&task->canceller,
self)) {
lntd_async_pool_complete(async_pool, task,
LNTD_ERROR_CANCELLED);
continue;
}
run_task(async_pool, task);
}
return 0;
}
#pragma weak lntd_sched_do_idle
#pragma weak lntd_io_do_poll
#pragma weak lntd_io_do_read
#pragma weak lntd_io_do_write
#pragma weak lntd_signal_do_wait
#pragma weak lntd_sched_do_sleep_until
static void run_task(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
switch (task->type) {
case LNTD_ASYNCH_TASK_IDLE:
lntd_sched_do_idle(pool, task);
return;
case LNTD_ASYNCH_TASK_POLL:
lntd_io_do_poll(pool, task);
return;
case LNTD_ASYNCH_TASK_READ:
lntd_io_do_read(pool, task);
return;
case LNTD_ASYNCH_TASK_WRITE:
lntd_io_do_write(pool, task);
return;
case LNTD_ASYNCH_TASK_SIGNAL_WAIT:
lntd_signal_do_wait(pool, task);
return;
case LNTD_ASYNCH_TASK_SLEEP_UNTIL:
lntd_sched_do_sleep_until(pool, task);
return;
default:
LNTD_ASSUME_UNREACHABLE();
}
}
struct wait_manager {
struct lntd_async_pool *async_pool;
struct waiter_queue *waiter_queue;
size_t poller_count;
pthread_t master_thread;
struct epoll_event *epoll_events;
struct lntd_async_waiter **waiters;
lntd_ko epoll_ko;
bool stopped : 1U;
};
static void *master_poller_routine(void *arg);
static lntd_error do_task_for_event(struct lntd_async_pool *async_pool,
struct lntd_async_waiter *waiter,
uint32_t revents);
static lntd_error recv_waiters(struct lntd_async_pool *async_pool,
pthread_t self, lntd_ko epoll_ko,
struct lntd_async_waiter **waiters,
struct waiter_queue *waiter_queue,
size_t max_tasks, uint32_t revents);
static lntd_error wait_manager_create(
struct wait_manager **managerp, struct waiter_queue *waiter_queue,
struct lntd_async_pool *async_pool, unsigned max_pollers)
{
LNTD_ASSERT_NOT_NULL(managerp);
LNTD_ASSERT_NOT_NULL(waiter_queue);
LNTD_ASSERT_NOT_NULL(async_pool);
lntd_error err;
struct wait_manager *manager;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *manager);
if (err != 0)
return err;
manager = xx;
}
struct lntd_async_waiter **waiters;
{
void *xx;
err = lntd_mem_alloc_array(&xx, max_pollers,
sizeof waiters[0U]);
if (err != 0)
goto free_manager;
waiters = xx;
}
struct epoll_event *epoll_events;
{
void *xx;
err = lntd_mem_alloc_array(&xx, max_pollers + 1U,
sizeof epoll_events[0U]);
if (err != 0)
goto free_waiters;
epoll_events = xx;
}
int epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (-1 == epoll_fd) {
err = errno;
LNTD_ASSUME(err != 0);
goto free_events;
}
manager->stopped = false;
manager->waiters = waiters;
manager->epoll_ko = epoll_fd;
manager->epoll_events = epoll_events;
manager->poller_count = max_pollers;
manager->waiter_queue = waiter_queue;
manager->async_pool = async_pool;
err = pthread_create(&manager->master_thread, 0,
master_poller_routine, manager);
if (err != 0)
goto close_epoll_fd;
*managerp = manager;
return 0;
close_epoll_fd:
lntd_ko_close(epoll_fd);
free_events:
lntd_mem_free(epoll_events);
free_waiters:
lntd_mem_free(waiters);
free_manager:
lntd_mem_free(manager);
return err;
}
static void wait_manager_destroy(struct wait_manager *manager)
{
LNTD_ASSERT_NOT_NULL(manager);
struct waiter_queue *waiter_queue = manager->waiter_queue;
pthread_t master_thread = manager->master_thread;
lntd_ko epoll_ko = manager->epoll_ko;
struct epoll_event *epoll_events = manager->epoll_events;
struct lntd_async_waiter **waiters = manager->waiters;
{
struct lntd_async_waiter waiter;
waiter.thread_canceller = true;
waiter_submit(waiter_queue, &waiter);
pthread_join(master_thread, 0);
}
lntd_ko_close(epoll_ko);
lntd_mem_free(epoll_events);
lntd_mem_free(waiters);
lntd_mem_free(manager);
}
static void *master_poller_routine(void *arg)
{
LNTD_ASSERT_NOT_NULL(arg);
pthread_t self = pthread_self();
lntd_proc_name("async-poller");
struct wait_manager *pool = arg;
struct waiter_queue *waiter_queue = pool->waiter_queue;
struct lntd_async_waiter **waiters = pool->waiters;
lntd_ko epoll_ko = pool->epoll_ko;
struct epoll_event *epoll_events = pool->epoll_events;
size_t max_tasks = pool->poller_count;
struct lntd_async_pool *async_pool = pool->async_pool;
for (size_t ii = 0U; ii < max_tasks; ++ii)
waiters[ii] = 0;
lntd_ko wait_ko = waiter_ko(waiter_queue);
lntd_error err = 0;
{
struct epoll_event xx = {0};
xx.events = EPOLLIN;
xx.data.u64 = 0U;
if (-1 ==
epoll_ctl(epoll_ko, EPOLL_CTL_ADD, wait_ko, &xx)) {
err = errno;
LNTD_ASSUME(err != 0);
goto exit_mainloop;
}
}
for (;;) {
int numpolled;
for (;;) {
numpolled = epoll_wait(epoll_ko, epoll_events,
1U + max_tasks, -1);
if (-1 == numpolled) {
err = errno;
LNTD_ASSUME(err != 0);
if (EINTR == err)
goto check_cancellers;
if (EAGAIN == err)
continue;
if (ENOMEM == err)
continue;
LNTD_ASSERT(err != EFAULT);
LNTD_ASSERT(
err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(0);
}
break;
}
for (size_t ii = 0U; ii < (unsigned)numpolled; ++ii) {
size_t index = epoll_events[ii].data.u64;
uint32_t revents = epoll_events[ii].events;
if (0U == index) {
err = recv_waiters(
async_pool, self, epoll_ko, waiters,
waiter_queue, max_tasks, revents);
if (ECANCELED == err) {
goto exit_mainloop;
}
continue;
}
struct lntd_async_waiter **waiterp =
&waiters[index - 1U];
struct lntd_async_waiter *waiter = *waiterp;
LNTD_ASSERT(waiter != 0);
err = do_task_for_event(async_pool, waiter,
revents);
if (err != 0)
goto exit_mainloop;
int fd = waiter->ko;
if (-1 ==
epoll_ctl(epoll_ko, EPOLL_CTL_DEL, fd, 0)) {
err = errno;
LNTD_ASSUME(err != 0);
goto exit_mainloop;
}
*waiterp = 0;
}
check_cancellers:
for (size_t ii = 0U; ii < max_tasks; ++ii) {
struct lntd_async_waiter *waiter = waiters[ii];
if (0 == waiter)
continue;
struct lntd_async_task *task = waiter->task;
if (!canceller_check_or_register(
&task->canceller, self))
continue;
if (-1 == epoll_ctl(epoll_ko, EPOLL_CTL_DEL,
waiter->ko, 0)) {
LNTD_ASSERT(0);
}
waiters[ii] = 0;
lntd_async_pool_complete(async_pool, task,
LNTD_ERROR_CANCELLED);
}
}
exit_mainloop:
return 0;
}
static lntd_error recv_waiters(struct lntd_async_pool *async_pool,
pthread_t self, lntd_ko epoll_ko,
struct lntd_async_waiter **waiters,
struct waiter_queue *waiter_queue,
size_t max_tasks, uint32_t revents)
{
lntd_error err = 0;
bool has_pollerr = (revents & EPOLLERR) != 0;
bool has_pollhup = (revents & EPOLLHUP) != 0;
bool has_pollin = (revents & EPOLLIN) != 0;
LNTD_ASSERT(!has_pollerr);
LNTD_ASSERT(!has_pollhup);
LNTD_ASSERT(has_pollin);
lntd_ko wait_ko = waiter_ko(waiter_queue);
for (;;) {
uint64_t xx;
if (-1 == read(wait_ko, &xx, sizeof xx)) {
err = errno;
LNTD_ASSERT(err != 0);
if (EINTR == err)
continue;
if (EAGAIN == err)
break;
LNTD_ASSERT(0);
}
break;
}
for (;;) {
struct lntd_async_waiter *waiter;
{
struct lntd_async_waiter *xx;
err = waiter_try_recv(waiter_queue, &xx);
if (EAGAIN == err)
break;
if (err != 0)
return err;
waiter = xx;
}
if (waiter->thread_canceller)
return ECANCELED;
lntd_ko ko = waiter->ko;
struct lntd_async_task *task = waiter->task;
uint32_t flags = waiter->flags;
if (canceller_check_or_register(&task->canceller,
self)) {
err = LNTD_ERROR_CANCELLED;
goto complete_task;
}
size_t jj = 0U;
for (; jj < max_tasks; ++jj) {
if (0 == waiters[jj])
goto finish;
}
LNTD_ASSERT(0);
finish:
waiters[jj] = waiter;
{
struct epoll_event xx = {0};
xx.events = flags | EPOLLONESHOT | EPOLLET;
xx.data.u64 = 1U + jj;
if (-1 == epoll_ctl(epoll_ko, EPOLL_CTL_ADD, ko,
&xx)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
}
continue;
complete_task:
lntd_async_pool_complete(async_pool, task, err);
continue;
}
return 0;
}
static lntd_error do_task_for_event(struct lntd_async_pool *async_pool,
struct lntd_async_waiter *waiter,
uint32_t revents)
{
struct lntd_async_task *task = waiter->task;
lntd_ko ko = waiter->ko;
bool has_pollerr = (revents & POLLERR) != 0;
bool has_pollnval = (revents & POLLNVAL) != 0;
lntd_error err = 0;
if (has_pollnval) {
err = LNTD_ERROR_INVALID_KO;
goto complete_task;
}
if (has_pollerr) {
int xx;
socklen_t yy = sizeof xx;
if (-1 ==
getsockopt(ko, SOL_SOCKET, SO_ERROR, &xx, &yy)) {
err = errno;
goto complete_task;
}
err = xx;
/* If another poller got the error then we could get
* zero instead so just resubmit in that case.
*/
if (err != 0)
goto complete_task;
}
waiter->revents = revents;
lntd_async_pool_resubmit(async_pool, task);
return 0;
complete_task:
lntd_async_pool_complete(async_pool, task, err);
return 0;
}
/* struct complete_queue is just a fake */
static lntd_error
completion_queue_create(struct completion_queue **queuep)
{
LNTD_ASSERT_NOT_NULL(queuep);
lntd_error err;
struct lntd_stack *queue;
{
struct lntd_stack *xx;
err = lntd_stack_create(&xx);
if (err != 0)
return err;
queue = xx;
}
*queuep = (struct completion_queue *)queue;
return 0;
}
static void complete_task(struct completion_queue *queue,
struct lntd_async_task *task)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(task);
lntd_stack_send((void *)queue, UPCAST(task));
}
static lntd_error completion_recv(struct completion_queue *queue,
struct lntd_async_task **taskp)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(taskp);
struct lntd_node *node;
{
struct lntd_node *xx;
lntd_stack_recv((void *)queue, &xx);
node = xx;
}
*taskp = DOWNCAST(struct lntd_async_task, node);
return 0;
}
static lntd_error completion_try_recv(struct completion_queue *queue,
struct lntd_async_task **taskp)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(taskp);
lntd_error err;
struct lntd_node *node;
{
struct lntd_node *xx;
err = lntd_stack_try_recv((void *)queue, &xx);
if (err != 0)
return err;
node = xx;
}
*taskp = DOWNCAST(struct lntd_async_task, node);
return 0;
}
static void completion_queue_destroy(struct completion_queue *queue)
{
lntd_stack_destroy((void *)queue);
}
/* struct job_queue is just a fake */
static lntd_error job_queue_create(struct job_queue **queuep)
{
LNTD_ASSERT_NOT_NULL(queuep);
lntd_error err;
struct lntd_stack *stack;
{
struct lntd_stack *xx;
err = lntd_stack_create(&xx);
if (err != 0)
return err;
stack = xx;
}
*queuep = (struct job_queue *)stack;
return 0;
}
static void job_submit(struct job_queue *queue,
struct lntd_async_task *task)
{
lntd_stack_send((void *)queue, UPCAST(task));
}
static lntd_error job_recv(struct job_queue *queue,
struct lntd_async_task **taskp)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(taskp);
struct lntd_node *node;
{
struct lntd_node *xx;
lntd_stack_recv((void *)queue, &xx);
node = xx;
}
*taskp = DOWNCAST(struct lntd_async_task, node);
return 0;
}
static void job_queue_destroy(struct job_queue *queue)
{
lntd_stack_destroy((void *)queue);
}
/* struct worker_queue is just a fake */
static lntd_error worker_queue_create(struct worker_queue **queuep)
{
LNTD_ASSERT_NOT_NULL(queuep);
lntd_error err;
struct lntd_channel *channel;
{
struct lntd_channel *xx;
err = lntd_channel_create(&xx);
if (err != 0)
return err;
channel = xx;
}
*queuep = (struct worker_queue *)channel;
return 0;
}
static lntd_error worker_try_submit(struct worker_queue *queue,
struct lntd_async_task *task)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(task);
return lntd_channel_try_send((struct lntd_channel *)queue,
task);
}
static lntd_error worker_recv(struct worker_queue *queue,
struct lntd_async_task **taskp)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(taskp);
struct lntd_async_task *task;
{
void *xx;
lntd_channel_recv((struct lntd_channel *)queue, &xx);
task = xx;
}
LNTD_ASSERT_NOT_NULL(task);
*taskp = task;
return 0;
}
static void worker_queue_destroy(struct worker_queue *queue)
{
lntd_channel_destroy((struct lntd_channel *)queue);
}
static lntd_error waiter_queue_create(struct waiter_queue **queuep)
{
LNTD_ASSERT_NOT_NULL(queuep);
lntd_error err = 0;
struct waiter_queue *queue;
{
struct lntd_ko_stack *xx;
err = lntd_ko_stack_create(&xx);
if (err != 0)
return err;
queue = (void *)xx;
}
*queuep = queue;
return 0;
}
static void waiter_queue_destroy(struct waiter_queue *queue)
{
lntd_ko_stack_destroy((void *)queue);
}
static lntd_ko waiter_ko(struct waiter_queue *queue)
{
return lntd_ko_stack_ko((void *)queue);
}
static void waiter_submit(struct waiter_queue *queue,
struct lntd_async_waiter *waiter)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(waiter);
lntd_ko_stack_send((void *)queue, UPCAST(waiter));
}
static lntd_error waiter_try_recv(struct waiter_queue *queue,
struct lntd_async_waiter **waiterp)
{
LNTD_ASSERT_NOT_NULL(queue);
LNTD_ASSERT_NOT_NULL(waiterp);
lntd_error err = 0;
struct lntd_async_waiter *waiter;
{
struct lntd_node *node;
err = lntd_ko_stack_try_recv((void *)queue, &node);
if (err != 0)
return err;
waiter = (void *)node;
}
*waiterp = waiter;
return 0;
}
static void canceller_init(struct canceller *canceller)
{
LNTD_ASSERT_NOT_NULL(canceller);
spinlock_init(&canceller->lock);
canceller->in_flight = false;
canceller->owned = false;
canceller->cancelled = false;
canceller->cancel_reply = false;
}
static void canceller_start(struct canceller *canceller)
{
LNTD_ASSERT_NOT_NULL(canceller);
lntd_error err;
spinlock *lock = &canceller->lock;
err = spinlock_lock(lock);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
LNTD_ASSERT(!canceller->in_flight);
LNTD_ASSERT(!canceller->owned);
canceller->cancelled = false;
canceller->cancel_reply = false;
canceller->in_flight = true;
canceller->owned = false;
err = spinlock_unlock(lock);
if (err != 0) {
LNTD_ASSERT(err != EPERM);
LNTD_ASSERT(false);
}
}
static void canceller_stop(struct canceller *canceller)
{
LNTD_ASSERT_NOT_NULL(canceller);
lntd_error err;
spinlock *lock = &canceller->lock;
err = spinlock_lock(lock);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
LNTD_ASSERT(canceller->owned);
LNTD_ASSERT(canceller->in_flight);
{
bool cancelled = canceller->cancelled;
if (cancelled)
canceller->cancel_reply = true;
canceller->cancelled = false;
}
canceller->in_flight = false;
canceller->owned = false;
err = spinlock_unlock(lock);
if (err != 0) {
LNTD_ASSERT(err != EPERM);
LNTD_ASSERT(false);
}
}
static void canceller_cancel(struct canceller *canceller)
{
LNTD_ASSERT_NOT_NULL(canceller);
lntd_error err;
spinlock *lock = &canceller->lock;
bool in_flight;
{
err = spinlock_lock(lock);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
LNTD_ASSERT(false == canceller->cancel_reply);
in_flight = canceller->in_flight;
if (in_flight) {
canceller->cancel_reply = false;
bool owned = canceller->owned;
if (owned) {
err = pthread_kill(canceller->owner,
LNTD_ASYNCH_SIGNO);
if (err != 0 && err != EAGAIN) {
LNTD_ASSERT(err != ESRCH);
LNTD_ASSERT(
err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(false);
}
}
}
canceller->cancelled = true;
err = spinlock_unlock(lock);
if (err != 0) {
LNTD_ASSERT(err != EPERM);
LNTD_ASSERT(false);
}
}
if (!in_flight)
return;
/* Yes, really, we do have to busy wait to prevent race
* conditions unfortunately */
bool cancel_replied;
do {
sched_yield();
err = spinlock_lock(lock);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
cancel_replied = canceller->cancel_reply;
if (!cancel_replied) {
bool owned = canceller->owned;
if (owned) {
err = pthread_kill(canceller->owner,
LNTD_ASYNCH_SIGNO);
if (err != 0 && err != EAGAIN) {
LNTD_ASSERT(err != ESRCH);
LNTD_ASSERT(
err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(false);
}
}
}
err = spinlock_unlock(lock);
if (err != 0) {
LNTD_ASSERT(err != EPERM);
LNTD_ASSERT(false);
}
} while (!cancel_replied);
}
static bool canceller_check_or_register(struct canceller *canceller,
pthread_t self)
{
LNTD_ASSERT_NOT_NULL(canceller);
lntd_error err;
spinlock *lock = &canceller->lock;
err = spinlock_lock(lock);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
bool cancelled = canceller->cancelled;
/* Don't actually complete the cancellation if cancelled and
* let the completion do that.
*/
canceller->owner = self;
canceller->owned = true;
err = spinlock_unlock(lock);
if (err != 0) {
LNTD_ASSERT(err != EPERM);
LNTD_ASSERT(false);
}
return cancelled;
}
static bool canceller_check_and_unregister(struct canceller *canceller)
{
lntd_error err;
err = spinlock_lock(&canceller->lock);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
LNTD_ASSERT(canceller->in_flight);
LNTD_ASSERT(canceller->owned);
canceller->owned = false;
bool cancelled = canceller->cancelled;
if (cancelled)
canceller->cancel_reply = true;
err = spinlock_unlock(&canceller->lock);
if (err != 0) {
LNTD_ASSERT(err != EPERM);
LNTD_ASSERT(false);
}
return cancelled;
}
#if defined _POSIX_SPIN_LOCKS
static inline void spinlock_init(spinlock *lock)
{
pthread_spin_init(lock, false);
}
static inline lntd_error spinlock_lock(spinlock *lock)
{
return pthread_spin_lock(lock);
}
static inline lntd_error spinlock_unlock(spinlock *lock)
{
return pthread_spin_unlock(lock);
}
#else
static inline void spinlock_init(spinlock *lock)
{
pthread_mutex_init(lock, 0);
}
static inline lntd_error spinlock_lock(spinlock *lock)
{
return pthread_mutex_lock(lock);
}
static inline lntd_error spinlock_unlock(spinlock *lock)
{
return pthread_mutex_unlock(lock);
}
#endif
static size_t small_stack_size(void)
{
/*
* Our tasks are only I/O tasks and have extremely tiny stacks.
*/
long maybe_page_size = sysconf(_SC_PAGE_SIZE);
LNTD_ASSERT(maybe_page_size >= 0);
long maybe_stack_min_size = sysconf(_SC_THREAD_STACK_MIN);
LNTD_ASSERT(maybe_stack_min_size >= 0);
size_t page_size = maybe_page_size;
size_t stack_min_size = maybe_stack_min_size;
return stack_min_size + page_size;
}
|
mstewartgallus/linted | src/async/test_async.c | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#include "lntd/async.h"
#include "lntd/error.h"
#include "lntd/log.h"
#include "lntd/sched.h"
#include "lntd/start.h"
#include "lntd/util.h"
#include <stddef.h>
#include <stdlib.h>
#define MAX_TASKS 20U
enum { ON_IDLE };
struct idle_data {
struct lntd_async_pool *pool;
unsigned long idle_count;
};
static void dispatch(union lntd_async_ck task_ck, void *userstate,
lntd_error err);
static void on_idle(struct lntd_sched_task_idle *idle_task,
lntd_error err);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-async-test"};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
struct idle_data idle_data[MAX_TASKS] = {0};
struct lntd_sched_task_idle *idle_task[MAX_TASKS];
for (size_t ii = 0U; ii < MAX_TASKS; ++ii) {
err = lntd_sched_task_idle_create(&idle_task[ii],
&idle_data[ii]);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_sched_task_idle: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
struct lntd_async_pool *pool;
{
struct lntd_async_pool *xx;
err = lntd_async_pool_create(&xx, MAX_TASKS);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_async_pool_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
pool = xx;
}
for (size_t ii = 0U; ii < MAX_TASKS; ++ii) {
idle_data[ii].pool = pool;
idle_data[ii].idle_count = 100U;
struct lntd_sched_task_idle *task = idle_task[ii];
lntd_sched_task_idle_submit(
pool, task, (union lntd_async_ck){.u64 = ON_IDLE},
task);
}
for (;;) {
struct lntd_async_result result;
{
struct lntd_async_result xx;
err = lntd_async_pool_wait(pool, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_async_pool_wait: "
"%s",
lntd_error_string(err));
return EXIT_FAILURE;
}
result = xx;
}
dispatch(result.task_ck, result.userstate, result.err);
for (size_t ii = 0U; ii < MAX_TASKS; ++ii) {
if (idle_data[ii].idle_count > 0U)
goto continue_loop;
}
goto exit_loop;
continue_loop:
continue;
}
exit_loop:
err = lntd_async_pool_destroy(pool);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_async_pool_destroy: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static void dispatch(union lntd_async_ck task_ck, void *userstate,
lntd_error err)
{
switch (task_ck.u64) {
case ON_IDLE:
on_idle(userstate, err);
break;
default:
LNTD_ASSUME_UNREACHABLE();
}
}
static void on_idle(struct lntd_sched_task_idle *idle_task,
lntd_error err)
{
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_sched_idle: %s",
lntd_error_string(err));
exit(EXIT_FAILURE);
}
struct idle_data *idle_data =
lntd_sched_task_idle_data(idle_task);
unsigned long count = idle_data->idle_count;
if (0U == count)
return;
idle_data->idle_count = count - 1U;
lntd_sched_task_idle_submit(
idle_data->pool, idle_task,
(union lntd_async_ck){.u64 = ON_IDLE}, idle_task);
}
|
mstewartgallus/linted | docs/platforms.h | <reponame>mstewartgallus/linted
/* Copyright (C) 2014, 2015 <NAME>
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty provided
* the copyright notice and this notice are preserved.
*/
/**
*
* @file
*
* Linted -- Platforms
*
* A list of platforms that final build products may or may not run
* on. This is different from build types because some platforms can
* run or emulate each others' build products.
*
* @section supported Supported Platforms
*
* These are the only supported platforms. Other platforms may work but
*are
* only worked on for the purpose of making the code more modular and
*better.
*
* @subsection x86_64-linux-gnu x86_64 GNU/Linux
*
* @subsubsection runtime Runtime Dependencies
*
* Direct library dependencies:
*
* - `libc6`
* - `libc6-dev`
* - `libcap-dev`
* - `libegl1-mesa`
* - `libegl1-mesa-dev`
* - `libgl1-mesa-glx`
* - `libgles2-mesa-dev`
* - `libglib2.0-0`
* - `libmagic1`
* - `libmirclientplatform-mesa`
* - `libpopt0`
* - `libpthread-stubs0-dev`
* - `libsigsegv2`
* - `libxau-dev`
* - `libxcb1`
* - `libxcb1-dev`
* - `libxcb-xkb-dev`
* - `libxdmcp-dev`
* - `libxkbcommon-dev`
* - `libxkbcommon-x11-dev`
* - `linux-libc-dev`
* - `x11proto-damage-dev`
* - `x11proto-kb-dev`
* - `x11proto-xf86vidmode-dev`
*
* Indirect:
*
* - `libdrm2`
* - `libffi6`
* - `libgbm1`
* - `libglapi-mesa`
* - `libwayland-client0`
* - `libwayland-server0`
* - `libx11-6`
* - `libx11-dev`
* - `libx11-xcb1`
* - `libxau6`
* - `libxcb-dri2-0`
* - `libxcb-xfixes0`
* - `libxdmcp6`
* - `x11proto-core-dev`
*
* Dependency descriptions:
*
* - libcap2
* - Main Site - https://sites.google.com/site/fullycapable/
* - Binaries
* - /lib/x86_64-linux-gnu/libcap.so.2.24
* - elfutils
* - Main Site - https://fedorahosted.org/elfutils/
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libelf-0.158.so
* - Linux Kernel
* - Main Site - https://www.kernel.org/
* - Bug Database - https://bugzilla.kernel.org/
* - Xorg X11 Server
* - Main Site - http://www.x.org/wiki/
* - Bug Database -
*https://bugs.freedesktop.org/describecomponents.cgi?product=xorg
* - Xorg X11 client libraries (Xlib, XCB, GLX)
* - Main Site - http://www.x.org/wiki/
* - Bug Database -
*https://bugs.freedesktop.org/describecomponents.cgi?product=xorg
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libX11.so.6.3.0
* - /usr/lib/x86_64-linux-gnu/libX11-xcb.so.1.0.0
* - /usr/lib/x86_64-linux-gnu/libXau.so.6.0.0
* - /usr/lib/x86_64-linux-gnu/libxcb.so.1.1.0
* - /usr/lib/x86_64-linux-gnu/libxcb-dri2.so.0.0.0
* - /usr/lib/x86_64-linux-gnu/libxcb-xfixes.so.0.0.0
* - /usr/lib/x86_64-linux-gnu/libXdmcp.so.6.0.0
* - /usr/lib/x86_64-linux-gnu/libXext.so.6.4.0
* - /usr/lib/x86_64-linux-gnu/libXfixes.so.3.1.0
* - /usr/lib/x86_64-linux-gnu/libpciaccess.so.0.11.1
* - Wayland
* - Main Site - http://wayland.freedesktop.org/
* - But Database -
*https://bugs.freedesktop.org/enter_bug.cgi?product=Wayland
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libwayland-client.so.0.2.0
* - /usr/lib/x86_64-linux-gnu/libwayland-server.so.0.1.0
* - DRI
* - Main Site - http://dri.freedesktop.org/wiki/
* - Bug Database -
*https://bugs.freedesktop.org/describecomponents.cgi?product=DRI
* - Binaries
* - /usr/lib/x86_64-linux-gnu/dri/i965_dri.so
* - /usr/lib/x86_64-linux-gnu/libgallium.so.0.0.0
* - /usr/lib/x86_64-linux-gnu/libdrm.so.2.4.0
* - /usr/lib/x86_64-linux-gnu/libdrm_intel.so.1.0.0
* - /usr/lib/x86_64-linux-gnu/libdrm_nouveau.so.2.0.0
* - /usr/lib/x86_64-linux-gnu/libdrm_radeon.so.1.0.1
* - Mesa
* - Main Site - http://www.mesa3d.org/
* - Bug Database -
*https://bugs.freedesktop.org/describecomponents.cgi?product=Mesa
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libgbm.so.1.0.0
* - /usr/lib/x86_64-linux-gnu/egl/egl_gallium.so
* - /usr/lib/x86_64-linux-gnu/mesa-egl/libEGL.so.1.0.0
* - /usr/lib/x86_64-linux-gnu/libglapi.so.0.0.0
* - /usr/lib/x86_64-linux-gnu/mesa-egl/libGLESv2.so.2.0.0
* - /usr/lib/x86_64-linux-gnu/mesa-egl/libOpenVG.so.1.0.0
* - s2tc
* - Main Site - https://github.com/divVerent/s2tc
* - Bug Database - https://github.com/divVerent/s2tc/issues
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libtxc_dxtn_s2tc.so.0.0.0
* - zlib
* - Main Site - http://zlib.net/
* - Binaries
* - /lib/x86_64-linux-gnu/libz.so.1.2.8
* - libffi
* - Main Site - https://sourceware.org/libffi/
* - Bug Database - https://github.com/atgreen/libffi/issues
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libffi.so.6.0.1
* - LLVM
* - Main Site - http://llvm.org/
* - Bug Database - http://llvm.org/bugs/
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libLLVM-3.4.so.1
* - The Expat XML Parser
* - Main Site - http://expat.sourceforge.net/
* - Bug Database - http://sourceforge.net/p/expat/bugs/
* - Binaries
* - /lib/x86_64-linux-gnu/libexpat.so.1.6.0
* - shared low-level terminfo library for terminal handling
* - Main Site - http://invisible-island.net/ncurses/
* - Binaries
* - /lib/x86_64-linux-gnu/libtinfo.so.5.9
* - GCC Support Library
* - Main Site - https://gcc.gnu.org/libstdc++/
* - Bug Mailing List - http://gcc.gnu.org/ml/gcc-bugs/
* - Bug Database - http://gcc.gnu.org/bugzilla/
* - Binaries
* - /lib/x86_64-linux-gnu/libgcc_s.so.1
* - The GNU Standard C++ Library
* - Main Site - https://gcc.gnu.org/libstdc++/
* - Bug Mailing List - http://gcc.gnu.org/ml/gcc-bugs/
* - Bug Database - http://gcc.gnu.org/bugzilla/
* - Binaries
* - /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19
* - The GNU C Library
* - Main Site - https://www.gnu.org/software/libc/
* - Bug Database -
*https://sourceware.org/bugzilla/describecomponents.cgi?product=glibc
* - Binaries
* - /lib/x86_64-linux-gnu/ld-2.19.so
* - /lib/x86_64-linux-gnu/libc-2.19.so
* - /lib/x86_64-linux-gnu/libdl-2.19.so
* - /lib/x86_64-linux-gnu/libm-2.19.so
* - /lib/x86_64-linux-gnu/libpthread-2.19.so
* - /lib/x86_64-linux-gnu/librt-2.19.so
* - Unknown user machine that implements the amd64 hardware
*architecture
*
* @subsection i686-linux-gnu i686 GNU/Linux
*
* Mostly the same as above but 32 bit.
*
* @section unsupported-platforms Unsupported Platforms
*
* These are not supported platform. They may work but are only
* worked on for a challenge and for making the code more modular and
* better. They may be supported.
*
* - x86_64 GNU/Linux Wine
* - x86_64 Microsoft Windows Vista (and greater)
*/
|
mstewartgallus/linted | src/linted-sandbox/sandbox-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/dir.h"
#include "lntd/error.h"
#include "lntd/execveat.h"
#include "lntd/fifo.h"
#include "lntd/file.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/locale.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/prctl.h"
#include "lntd/start.h"
#include "lntd/str.h"
#include "lntd/util.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <fcntl.h>
#include <limits.h>
#include <mntent.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/capability.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <syscall.h>
#include <unistd.h>
#include <wordexp.h>
#include <linux/seccomp.h>
#include <seccomp.h>
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000
#endif
/**
* @file
*
* Sandbox applications.
*
* @bug `mount("/home", "home", "none", MS_SHARED | MS_BIND)` doesn't
* work if `/home` has a userspace filesystem mounted inside of
* it.
*/
enum { STOP_OPTIONS,
HELP,
VERSION_OPTION,
WAIT,
TRACEME,
DROP_CAPS,
NO_NEW_PRIVS,
LIMIT_NO_FILE,
LIMIT_LOCKS,
LIMIT_MSGQUEUE,
LIMIT_MEMLOCK,
CHDIR,
PRIORITY,
TIMER_SLACK,
CHROOTDIR,
FSTAB,
WAITER,
SECCOMP_FILTER,
SECCOMP_NATIVE,
NEWCGROUP_ARG,
NEWUSER_ARG,
NEWPID_ARG,
NEWIPC_ARG,
NEWNET_ARG,
NEWNS_ARG,
NEWUTS_ARG,
NUM_OPTIONS };
struct mount_args {
char const *fsname;
char *dir;
char const *type;
char const *data;
unsigned long mountflags;
bool mkdir_flag : 1U;
bool touch_flag : 1U;
bool nomount_flag : 1U;
};
static char const *const argstrs[NUM_OPTIONS] = {
/**/[STOP_OPTIONS] = "--",
/**/ [HELP] = "--help",
/**/ [VERSION_OPTION] = "--version",
/**/ [WAIT] = "--wait",
/**/ [TRACEME] = "--traceme",
/**/ [DROP_CAPS] = "--dropcaps",
/**/ [NO_NEW_PRIVS] = "--nonewprivs",
/**/ [LIMIT_NO_FILE] = "--limit-no-file",
/**/ [LIMIT_LOCKS] = "--limit-locks",
/**/ [LIMIT_MSGQUEUE] = "--limit-msgqueue",
/**/ [LIMIT_MEMLOCK] = "--limit-memlock",
/**/ [CHDIR] = "--chdir",
/**/ [PRIORITY] = "--priority",
/**/ [TIMER_SLACK] = "--timer-slack",
/**/ [CHROOTDIR] = "--chrootdir",
/**/ [FSTAB] = "--fstab",
/**/ [WAITER] = "--waiter",
/**/ [SECCOMP_FILTER] = "--seccomp-filter",
/**/ [SECCOMP_NATIVE] = "--seccomp-arch-native",
/**/ [NEWUSER_ARG] = "--clone-newuser",
/**/ [NEWPID_ARG] = "--clone-newpid",
/**/ [NEWIPC_ARG] = "--clone-newipc",
/**/ [NEWNET_ARG] = "--clone-newnet",
/**/ [NEWCGROUP_ARG] = "--clone-newcgroup",
/**/ [NEWNS_ARG] = "--clone-newns",
/**/ [NEWUTS_ARG] = "--clone-newuts"};
enum { OPT_TYPE_FLAG,
OPT_TYPE_STRING,
};
union opt_value {
bool flag;
char const *string;
};
static uint_least8_t opt_types[NUM_OPTIONS] = {
/**/[STOP_OPTIONS] = OPT_TYPE_FLAG,
/**/ [HELP] = OPT_TYPE_FLAG,
/**/ [VERSION_OPTION] = OPT_TYPE_FLAG,
/**/ [WAIT] = OPT_TYPE_FLAG,
/**/ [TRACEME] = OPT_TYPE_FLAG,
/**/ [DROP_CAPS] = OPT_TYPE_FLAG,
/**/ [NO_NEW_PRIVS] = OPT_TYPE_FLAG,
/**/ [LIMIT_NO_FILE] = OPT_TYPE_STRING,
/**/ [LIMIT_LOCKS] = OPT_TYPE_STRING,
/**/ [LIMIT_MSGQUEUE] = OPT_TYPE_STRING,
/**/ [LIMIT_MEMLOCK] = OPT_TYPE_STRING,
/**/ [CHDIR] = OPT_TYPE_STRING,
/**/ [PRIORITY] = OPT_TYPE_STRING,
/**/ [TIMER_SLACK] = OPT_TYPE_STRING,
/**/ [CHROOTDIR] = OPT_TYPE_STRING,
/**/ [FSTAB] = OPT_TYPE_STRING,
/**/ [WAITER] = OPT_TYPE_STRING,
/**/ [SECCOMP_FILTER] = OPT_TYPE_STRING,
/**/ [SECCOMP_NATIVE] = OPT_TYPE_FLAG,
/**/ [NEWUSER_ARG] = OPT_TYPE_FLAG,
/**/ [NEWPID_ARG] = OPT_TYPE_FLAG,
/**/ [NEWIPC_ARG] = OPT_TYPE_FLAG,
/**/ [NEWNET_ARG] = OPT_TYPE_FLAG,
/**/ [NEWNS_ARG] = OPT_TYPE_FLAG,
/**/ [NEWUTS_ARG] = OPT_TYPE_FLAG,
};
struct first_fork_args {
char const *chdir_path;
cap_t caps;
struct mount_args *mount_args;
size_t mount_args_size;
char const *waiter;
char const *waiter_base;
char const *const *command;
char const *binary;
int_least64_t limit_no_file;
scmp_filter_ctx *seccomp_context;
lntd_ko err_writer;
lntd_ko logger_reader;
lntd_ko logger_writer;
bool limit_no_file_set;
};
struct second_fork_args {
char const *const *argv;
char const *binary;
int_least64_t limit_no_file;
scmp_filter_ctx *seccomp_context;
lntd_ko err_writer;
lntd_ko logger_writer;
bool limit_no_file_set;
};
static int first_fork_routine(void *arg);
static int second_fork_routine(void *arg);
static lntd_error do_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport);
static lntd_error parse_mount_opts(char const *opts, bool *mkdir_flagp,
bool *touch_flagp,
bool *nomount_flagp,
unsigned long *mountflagsp,
char const **leftoversp);
static lntd_error set_id_maps(char const *uid_map, char const *gid_map);
static lntd_error mount_directories(struct mount_args const *mount_args,
size_t size);
static lntd_error set_child_subreaper(bool v);
static lntd_error parse_int(char const *str, int *resultp);
static lntd_error safe_dup2(int oldfd, int newfd);
static pid_t safe_vfork(int (*f)(void *), void *args);
static int my_pivot_root(char const *new_root, char const *put_old);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-sandbox",
.dont_init_signals = true};
union opt_value opt_values[NUM_OPTIONS] = {0};
static unsigned char lntd_start_main(char const *const process_name,
size_t argc,
char const *const argv[])
{
lntd_error err;
size_t arguments_length = argc;
char const *bad_option = 0;
bool have_command = false;
size_t command_start;
bool need_version;
bool need_help;
bool wait;
bool traceme;
bool no_new_privs;
bool drop_caps;
bool clone_newcgroup;
bool clone_newuser;
bool clone_newpid;
bool clone_newipc;
bool clone_newnet;
bool clone_newns;
bool clone_newuts;
bool seccomp_native;
char const *limit_no_file_str;
char const *limit_locks_str;
char const *limit_msgqueue_str;
char const *limit_memlock_str;
char const *chdir_str;
char const *priority_str;
char const *timer_slack_str;
char const *chrootdir_str;
char const *fstab_str;
char const *waiter_str;
char const *seccomp_filter_str;
for (size_t ii = 1U; ii < arguments_length; ++ii) {
char const *argument = argv[ii];
int arg = -1;
for (size_t jj = 0U; jj < LNTD_ARRAY_SIZE(argstrs);
++jj) {
if (0 == strcmp(argument, argstrs[jj])) {
arg = jj;
break;
}
}
switch (arg) {
case -1:
bad_option = argument;
break;
case STOP_OPTIONS:
have_command = true;
command_start = ii;
goto exit_loop;
default:
switch (opt_types[arg]) {
case OPT_TYPE_FLAG:
opt_values[arg].flag = true;
break;
case OPT_TYPE_STRING:
++ii;
if (ii >= arguments_length)
goto exit_loop;
opt_values[arg].string = argv[ii];
break;
}
break;
}
}
exit_loop:
need_version = opt_values[VERSION_OPTION].flag;
need_help = opt_values[HELP].flag;
wait = opt_values[WAIT].flag;
traceme = opt_values[TRACEME].flag;
no_new_privs = opt_values[NO_NEW_PRIVS].flag;
drop_caps = opt_values[DROP_CAPS].flag;
clone_newcgroup = opt_values[NEWCGROUP_ARG].flag;
clone_newuser = opt_values[NEWUSER_ARG].flag;
clone_newpid = opt_values[NEWPID_ARG].flag;
clone_newipc = opt_values[NEWIPC_ARG].flag;
clone_newnet = opt_values[NEWNET_ARG].flag;
clone_newns = opt_values[NEWNS_ARG].flag;
clone_newuts = opt_values[NEWUTS_ARG].flag;
seccomp_native = opt_values[SECCOMP_NATIVE].flag;
limit_no_file_str = opt_values[RLIMIT_NOFILE].string;
limit_locks_str = opt_values[LIMIT_LOCKS].string;
limit_msgqueue_str = opt_values[LIMIT_MSGQUEUE].string;
limit_memlock_str = opt_values[LIMIT_MEMLOCK].string;
chdir_str = opt_values[CHDIR].string;
priority_str = opt_values[PRIORITY].string;
timer_slack_str = opt_values[TIMER_SLACK].string;
chrootdir_str = opt_values[CHROOTDIR].string;
fstab_str = opt_values[FSTAB].string;
waiter_str = opt_values[WAITER].string;
seccomp_filter_str = opt_values[SECCOMP_FILTER].string;
if (need_help) {
do_help(LNTD_KO_STDOUT, process_name, PACKAGE_NAME,
PACKAGE_URL, PACKAGE_BUGREPORT);
return EXIT_SUCCESS;
}
if (bad_option != 0) {
lntd_log(LNTD_LOG_ERROR, "bad option: %s", bad_option);
return EXIT_FAILURE;
}
if (need_version) {
lntd_locale_version(LNTD_KO_STDOUT, PACKAGE_STRING,
COPYRIGHT_YEAR);
return EXIT_SUCCESS;
}
if (!have_command) {
lntd_log(LNTD_LOG_ERROR, "need command");
return EXIT_FAILURE;
}
if (0 == waiter_str) {
lntd_log(LNTD_LOG_ERROR, "need waiter");
return EXIT_FAILURE;
}
if ((fstab_str != 0 && 0 == chrootdir_str) ||
(0 == fstab_str && chrootdir_str != 0)) {
lntd_log(
LNTD_LOG_ERROR,
"--chrootdir and --fstab are required together");
return EXIT_FAILURE;
}
if (traceme) {
/* Register with the parent */
if (-1 == raise(SIGSTOP)) {
lntd_log(LNTD_LOG_ERROR, "raise: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
char const *const *command = argv + 1U + command_start;
size_t command_size = argc - (1U + command_start);
char **command_dup;
{
void *xx;
err = lntd_mem_alloc_array(&xx, command_size + 1U,
sizeof command_dup[0U]);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_mem_alloc_array: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
command_dup = xx;
}
command_dup[command_size] = 0;
for (size_t ii = 0U; ii < command_size; ++ii) {
char const *c = command[ii];
char *xx = 0;
err = lntd_str_dup(&xx, c);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_str_dup: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
command_dup[ii] = xx;
}
char *waiter_base;
{
char *xx;
err = lntd_path_base(&xx, waiter_str);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_path_base: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
waiter_base = xx;
}
char *command_base;
{
char const *c = command_dup[0U];
char *xx;
err = lntd_path_base(&xx, c);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_path_base: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
command_base = xx;
}
lntd_mem_free(command_dup[0U]);
command_dup[0U] = command_base;
char const *binary = command[0U];
int_least64_t prio_val = 0;
bool prio_val_set = priority_str != 0;
if (prio_val_set) {
int xx;
err = parse_int(priority_str, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "parse_int: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
prio_val = xx;
}
int_least64_t timer_slack_val = 0;
bool timer_slack_val_set = timer_slack_str != 0;
if (timer_slack_val_set) {
int xx;
err = parse_int(timer_slack_str, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "parse_int: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
timer_slack_val = xx;
}
int_least64_t limit_no_file_val = 0;
bool limit_no_file_val_set = limit_no_file_str != 0;
if (limit_no_file_val_set) {
int xx;
err = parse_int(limit_no_file_str, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "parse_int: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
limit_no_file_val = xx;
}
int_least64_t limit_locks_val = 0;
bool limit_locks_val_set = limit_locks_str != 0;
if (limit_locks_val_set) {
int xx;
err = parse_int(limit_locks_str, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "parse_int: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
limit_locks_val = xx;
}
int_least64_t limit_msgqueue_val = 0;
bool limit_msgqueue_val_set = limit_msgqueue_str != 0;
if (limit_msgqueue_val_set) {
int xx;
err = parse_int(limit_msgqueue_str, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "parse_int: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
limit_msgqueue_val = xx;
}
int_least64_t limit_memlock_val = 0;
bool limit_memlock_val_set = limit_memlock_str != 0;
if (limit_memlock_val_set) {
int xx;
err = parse_int(limit_memlock_str, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "parse_int: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
limit_memlock_val = xx;
}
size_t mount_args_size = 0U;
struct mount_args *mount_args = 0;
if (fstab_str != 0) {
FILE *fstab_file = fopen(fstab_str, "re");
if (0 == fstab_file) {
lntd_log(LNTD_LOG_ERROR, "fopen(%s): %s",
fstab_str, lntd_error_string(errno));
return EXIT_FAILURE;
}
char *buf = 0;
size_t buf_size = 0U;
for (;;) {
errno = 0;
size_t line_size;
{
char *xx = buf;
size_t yy = buf_size;
ssize_t zz =
getline(&xx, &yy, fstab_file);
if (zz < 0) {
err = errno;
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"getlines: %s",
lntd_error_string(
err));
return EXIT_FAILURE;
}
break;
}
buf = xx;
buf_size = yy;
line_size = zz;
}
if ('#' == buf[0U])
continue;
if ('\0' == buf[0U])
continue;
if ('\n' == buf[line_size - 1U])
buf[line_size - 1U] = '\0';
wordexp_t expr;
{
wordexp_t xx;
switch (wordexp(buf, &xx, WRDE_NOCMD)) {
case WRDE_BADCHAR:
case WRDE_CMDSUB:
case WRDE_SYNTAX:
err = EINVAL;
break;
case WRDE_NOSPACE:
err = LNTD_ERROR_OUT_OF_MEMORY;
break;
}
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"wordexp(%s): %s", buf,
lntd_error_string(err));
return EXIT_FAILURE;
}
expr = xx;
}
char const *const *words =
(char const *const *)expr.we_wordv;
char const *fsname = 0;
char const *dir = 0;
char const *type = 0;
char const *opts = 0;
fsname = words[0U];
if (0 == fsname)
goto free_words;
dir = words[1U];
if (0 == dir)
goto parse_expr;
type = words[2U];
if (0 == type)
goto parse_expr;
opts = words[3U];
if (0 == type)
goto parse_expr;
parse_expr:
if (0 == strcmp("none", fsname))
fsname = 0;
if (0 == strcmp("none", opts))
opts = 0;
bool mkdir_flag = false;
bool touch_flag = false;
bool nomount_flag = false;
unsigned long mountflags = 0U;
char const *data = 0;
if (opts != 0) {
bool xx;
bool yy;
bool zz;
unsigned long ww;
char const *uu;
err = parse_mount_opts(opts, &xx, &yy,
&zz, &ww, &uu);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"parse_mount_opts: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
mkdir_flag = xx;
touch_flag = yy;
nomount_flag = zz;
mountflags = ww;
data = uu;
}
size_t new_mount_args_size =
mount_args_size + 1U;
{
void *xx;
err = lntd_mem_realloc_array(
&xx, mount_args,
new_mount_args_size,
sizeof mount_args[0U]);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_mem_realloc_"
"array: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
mount_args = xx;
}
if (fsname != 0) {
char *xx;
err = lntd_str_dup(&xx, fsname);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_str_dup: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
fsname = xx;
}
if (dir != 0) {
char *xx;
err = lntd_str_dup(&xx, dir);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_str_dup: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
dir = xx;
}
if (type != 0) {
char *xx;
err = lntd_str_dup(&xx, type);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_str_dup: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
type = xx;
}
if (data != 0) {
char *xx;
err = lntd_str_dup(&xx, data);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_str_dup: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
data = xx;
}
char *dir_dup;
{
char *xx;
err = lntd_str_dup(&xx, dir);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_str_dup: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
dir_dup = xx;
}
struct mount_args *new_mount_arg =
&mount_args[mount_args_size];
new_mount_arg->fsname = fsname;
new_mount_arg->dir = dir_dup;
new_mount_arg->type = type;
new_mount_arg->data = data;
new_mount_arg->mountflags = mountflags;
new_mount_arg->mkdir_flag = mkdir_flag;
new_mount_arg->touch_flag = touch_flag;
new_mount_arg->nomount_flag = nomount_flag;
mount_args_size = new_mount_args_size;
free_words : {
wordexp_t xx = expr;
wordfree(&xx);
}
}
if (fclose(fstab_file) != 0) {
lntd_log(LNTD_LOG_ERROR, "fclose: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
gid_t gid = getgid();
uid_t uid = getuid();
gid_t mapped_gid = gid;
uid_t mapped_uid = uid;
char const *uid_map;
char const *gid_map;
{
char *xx;
if (-1 == asprintf(&xx, "%i %i 1\n", mapped_uid, uid)) {
lntd_log(LNTD_LOG_ERROR, "asprintf: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
uid_map = xx;
}
{
char *xx;
if (-1 == asprintf(&xx, "%i %i 1\n", mapped_gid, gid)) {
lntd_log(LNTD_LOG_ERROR, "asprintf: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
gid_map = xx;
}
lntd_ko logger_reader;
lntd_ko logger_writer;
{
int xx[2U];
if (-1 == pipe2(xx, O_CLOEXEC)) {
lntd_log(LNTD_LOG_ERROR, "pipe2: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
logger_reader = xx[0U];
logger_writer = xx[1U];
}
lntd_ko err_reader;
lntd_ko err_writer;
{
lntd_ko xx;
lntd_ko yy;
err = lntd_fifo_pair(&xx, &yy, 0);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_fifo_pair: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
err_reader = xx;
err_writer = yy;
}
cap_t caps = 0;
if (drop_caps) {
caps = cap_get_proc();
if (0 == caps) {
lntd_log(LNTD_LOG_ERROR, "cap_get_proc: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
if (-1 == cap_clear_flag(caps, CAP_EFFECTIVE)) {
lntd_log(LNTD_LOG_ERROR, "cap_clear_flag: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
if (-1 == cap_clear_flag(caps, CAP_PERMITTED)) {
lntd_log(LNTD_LOG_ERROR, "cap_clear_flag: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
if (-1 == cap_clear_flag(caps, CAP_INHERITABLE)) {
lntd_log(LNTD_LOG_ERROR, "cap_clear_flag: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
scmp_filter_ctx *seccomp_context = 0;
if (seccomp_native || seccomp_filter_str != 0) {
seccomp_context = seccomp_init(SCMP_ACT_KILL);
if (0 == seccomp_context) {
lntd_log(LNTD_LOG_ERROR, "seccomp_init: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
if (0 == seccomp_filter_str) {
seccomp_reset(seccomp_context, SCMP_ACT_ALLOW);
} else {
char const *start = seccomp_filter_str;
for (;;) {
char *end = strchr(start, ',');
size_t size;
if (0 == end) {
size = strlen(start);
} else {
size = end - start;
}
char *syscall_str;
{
char *xx;
err = lntd_str_dup_len(
&xx, start, size);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_str_dup: %s",
lntd_error_string(
err));
return EXIT_FAILURE;
}
syscall_str = xx;
}
start = end + 1U;
int sysno =
seccomp_syscall_resolve_name(
syscall_str);
if (__NR_SCMP_ERROR == sysno) {
lntd_log(LNTD_LOG_ERROR,
"seccomp_syscall_"
"resolve_name: %s",
syscall_str);
return EXIT_FAILURE;
}
lntd_mem_free(syscall_str);
err = -seccomp_rule_add(seccomp_context,
SCMP_ACT_ALLOW,
sysno, 0);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"seccomp_rule_add: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
if (0 == end)
break;
}
}
}
int clone_flags = 0;
if (clone_newcgroup)
clone_flags |= CLONE_NEWCGROUP;
if (clone_newuser)
clone_flags |= CLONE_NEWUSER;
if (clone_newipc)
clone_flags |= CLONE_NEWIPC;
if (clone_newns)
clone_flags |= CLONE_NEWNS;
if (clone_newuts)
clone_flags |= CLONE_NEWUTS;
if (clone_newnet)
clone_flags |= CLONE_NEWNET;
if (clone_newpid)
clone_flags |= CLONE_NEWPID;
/* Only start actually dropping privileges now */
if (timer_slack_val_set) {
err = lntd_prctl_set_timerslack(timer_slack_val);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "prctl: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
if (prio_val_set) {
if (-1 == setpriority(PRIO_PROCESS, 0, prio_val)) {
lntd_log(LNTD_LOG_ERROR, "setpriority: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
if (no_new_privs) {
/* Must appear before the seccomp filter */
err = lntd_prctl_set_no_new_privs(true);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "prctl: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
if (clone_flags != 0) {
if (-1 == unshare(clone_flags)) {
lntd_log(LNTD_LOG_ERROR, "unshare: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
if (clone_newuser) {
err = set_id_maps(uid_map, gid_map);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "set_id_maps: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
if (chrootdir_str != 0) {
if (-1 == mount(chrootdir_str, chrootdir_str, 0,
MS_BIND, 0)) {
lntd_log(LNTD_LOG_ERROR, "mount: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
if (-1 == chdir(chrootdir_str)) {
lntd_log(LNTD_LOG_ERROR, "chdir: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
if (limit_locks_val_set) {
struct rlimit const lim = {
.rlim_cur = limit_locks_val,
.rlim_max = limit_locks_val,
};
if (-1 == setrlimit(RLIMIT_LOCKS, &lim)) {
lntd_log(LNTD_LOG_ERROR, "setrlimit: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
if (limit_msgqueue_val_set) {
struct rlimit const lim = {
.rlim_cur = limit_msgqueue_val,
.rlim_max = limit_msgqueue_val,
};
if (-1 == setrlimit(RLIMIT_MSGQUEUE, &lim)) {
lntd_log(LNTD_LOG_ERROR, "setrlimit: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
if (limit_memlock_val_set) {
struct rlimit const lim = {
.rlim_cur = limit_memlock_val,
.rlim_max = limit_memlock_val,
};
if (-1 == setrlimit(RLIMIT_MEMLOCK, &lim)) {
lntd_log(LNTD_LOG_ERROR, "setrlimit: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
pid_t child;
{
struct first_fork_args args = {
.err_writer = err_writer,
.limit_no_file = limit_no_file_val,
.limit_no_file_set = limit_no_file_val_set,
.logger_reader = logger_reader,
.logger_writer = logger_writer,
.chdir_path = chdir_str,
.caps = caps,
.mount_args = mount_args,
.mount_args_size = mount_args_size,
.seccomp_context = seccomp_context,
.waiter_base = waiter_base,
.waiter = waiter_str,
.command = (char const *const *)command_dup,
.binary = binary};
child = safe_vfork(first_fork_routine, &args);
}
if (-1 == child) {
lntd_log(LNTD_LOG_ERROR, "clone: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
lntd_ko_close(err_writer);
{
size_t xx;
lntd_error yy;
err = lntd_io_read_all(err_reader, &xx, &yy, sizeof yy);
if (err != 0)
goto close_err_reader;
/* If bytes_read is zero then a succesful exec
* occured */
if (xx == sizeof yy)
err = yy;
}
close_err_reader:
lntd_ko_close(err_reader);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "spawning: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
if (!wait)
return EXIT_SUCCESS;
lntd_ko_close(LNTD_KO_STDIN);
lntd_ko_close(LNTD_KO_STDOUT);
for (;;) {
int xx;
switch (waitpid(child, &xx, 0)) {
case -1:
switch (errno) {
case EINTR:
continue;
default:
lntd_log(LNTD_LOG_ERROR, "waitpid: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
default:
return EXIT_SUCCESS;
}
}
}
static lntd_error set_id_maps(char const *uid_map, char const *gid_map)
{
lntd_error err;
lntd_ko set_groups;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD,
"/proc/thread-self/setgroups",
LNTD_KO_WRONLY);
if (err != 0)
return err;
set_groups = xx;
}
err = lntd_io_write_string(set_groups, 0, "deny");
if (err != 0)
return err;
err = lntd_ko_close(set_groups);
if (err != 0)
return err;
/* Note that writing to uid_map and gid_map will fail if the
* binary is not dumpable. DON'T set the process dumpable and
* fail if the process is nondumpable as presumably the
* invoker of the process had good reasons to have the process
* nondumpable.
*/
lntd_ko uid_file;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD,
"/proc/thread-self/uid_map",
LNTD_KO_WRONLY);
if (err != 0)
return err;
uid_file = xx;
}
err = lntd_io_write_string(uid_file, 0, uid_map);
if (err != 0)
return err;
err = lntd_ko_close(uid_file);
if (err != 0)
return err;
lntd_ko gid_file;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD,
"/proc/thread-self/gid_map",
LNTD_KO_WRONLY);
if (err != 0)
return err;
gid_file = xx;
}
err = lntd_io_write_string(gid_file, 0, gid_map);
if (err != 0)
return err;
err = lntd_ko_close(gid_file);
if (err != 0)
return err;
return 0;
}
LNTD_NO_SANITIZE_ADDRESS static int first_fork_routine(void *void_args)
{
lntd_error err = 0;
struct first_fork_args const *first_fork_args = void_args;
int_least64_t limit_no_file = first_fork_args->limit_no_file;
bool limit_no_file_set = first_fork_args->limit_no_file_set;
lntd_ko err_writer = first_fork_args->err_writer;
lntd_ko logger_reader = first_fork_args->logger_reader;
lntd_ko logger_writer = first_fork_args->logger_writer;
char const *chdir_path = first_fork_args->chdir_path;
cap_t caps = first_fork_args->caps;
struct mount_args *mount_args = first_fork_args->mount_args;
size_t mount_args_size = first_fork_args->mount_args_size;
scmp_filter_ctx *seccomp_context =
first_fork_args->seccomp_context;
char const *waiter = first_fork_args->waiter;
char const *waiter_base = first_fork_args->waiter_base;
char const *const *command = first_fork_args->command;
char const *binary = first_fork_args->binary;
/* The setsid() function creates a new session, if the calling
* process is not a process group leader. Upon return the
* calling process will be the session leader of this new
* session, will be the process group leader of a new process
* group, and will have no controlling terminal.
*
* - setsid(2) The Single UNIX ® Specification, Version 2
*/
/* So we don't need to explicitly set that there is no
* controlling terminal. */
if (-1 == setsid()) {
err = errno;
goto fail;
}
/* For some reason we must mount directories after we actually
* become PID 1 in the new pid namespace so that we can mount
* procfs */
lntd_ko waiter_ko;
if (mount_args_size > 0U) {
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, waiter, 0);
if (err != 0)
goto fail;
waiter_ko = xx;
}
err = mount_directories(mount_args, mount_args_size);
if (err != 0)
goto fail;
}
if (chdir_path != 0) {
if (-1 == chdir(chdir_path)) {
err = errno;
goto fail;
}
}
/*
* Don't create stuff usable by other processes by default
*/
umask(0777);
/*
* This isn't needed if CLONE_NEWPID was used but it doesn't
* hurt,
*/
err = set_child_subreaper(true);
if (err != 0)
goto fail;
/* Drop all capabilities I might possibly have. Note that
* currently we do not use PR_SET_KEEPCAPS and do not map our
* sandboxed user to root but if we did in the future we would
* need this.
*/
if (caps != 0) {
if (-1 == cap_set_proc(caps)) {
err = errno;
goto fail;
}
}
lntd_ko vfork_err_reader;
lntd_ko vfork_err_writer;
{
int xx[2U];
if (-1 == pipe2(xx, O_CLOEXEC | O_NONBLOCK)) {
err = errno;
goto fail;
}
vfork_err_reader = xx[0U];
vfork_err_writer = xx[1U];
}
pid_t grand_child;
struct second_fork_args args = {
.err_writer = vfork_err_writer,
.limit_no_file = limit_no_file,
.limit_no_file_set = limit_no_file_set,
.logger_writer = logger_writer,
.binary = binary,
.argv = command,
.seccomp_context = seccomp_context};
grand_child = safe_vfork(second_fork_routine, &args);
if (-1 == grand_child) {
err = errno;
goto fail;
}
lntd_ko_close(vfork_err_writer);
{
size_t xx;
lntd_error yy;
err = lntd_io_read_all(vfork_err_reader, &xx, &yy,
sizeof yy);
if (err != 0)
goto fail;
/* If bytes_read is zero then a succesful exec
* occured */
if (xx == sizeof yy)
err = yy;
}
if (err != 0)
goto fail;
err = safe_dup2(logger_reader, LNTD_KO_STDIN);
if (err != 0)
goto fail;
{
char const *const arguments[] = {waiter_base, 0};
if (mount_args_size > 0U) {
err = lntd_execveat(waiter_ko, "",
(char **)arguments, environ,
AT_EMPTY_PATH);
} else {
execve(waiter, (char *const *)arguments,
environ);
err = errno;
LNTD_ASSUME(err != 0);
}
}
fail : {
lntd_error xx = err;
lntd_io_write_all(err_writer, 0, &xx, sizeof xx);
}
return EXIT_FAILURE;
}
LNTD_NO_SANITIZE_ADDRESS static int second_fork_routine(void *arg)
{
lntd_error err;
struct second_fork_args const *args = arg;
int_least64_t limit_no_file = args->limit_no_file;
bool limit_no_file_set = args->limit_no_file_set;
lntd_ko err_writer = args->err_writer;
lntd_ko logger_writer = args->logger_writer;
char const *const *argv = args->argv;
scmp_filter_ctx seccomp_context = args->seccomp_context;
char const *binary = args->binary;
err = safe_dup2(logger_writer, LNTD_KO_STDOUT);
if (err != 0)
goto fail;
err = safe_dup2(logger_writer, LNTD_KO_STDERR);
if (err != 0)
goto fail;
if (limit_no_file_set) {
struct rlimit const lim = {
.rlim_cur = limit_no_file,
.rlim_max = limit_no_file,
};
if (-1 == setrlimit(RLIMIT_NOFILE, &lim)) {
err = errno;
LNTD_ASSUME(err != 0);
LNTD_ASSERT(err != EINVAL);
goto fail;
}
}
/* Do seccomp filter last of all */
if (seccomp_context != 0) {
err = -seccomp_load(seccomp_context);
if (err != 0)
goto fail;
}
execve(binary, (char *const *)argv, environ);
err = errno;
fail : {
lntd_error xx = err;
lntd_io_write_all(err_writer, 0, &xx, sizeof xx);
}
return EXIT_FAILURE;
}
LNTD_NO_SANITIZE_ADDRESS static lntd_error
mount_directories(struct mount_args const *mount_args, size_t size)
{
lntd_error err;
for (size_t ii = 0U; ii < size; ++ii) {
struct mount_args const *arg = &mount_args[ii];
char const *fsname = arg->fsname;
char *dir = arg->dir;
char const *type = arg->type;
char const *data = arg->data;
bool mkdir_flag = arg->mkdir_flag;
bool touch_flag = arg->touch_flag;
bool nomount_flag = arg->nomount_flag;
unsigned long mountflags = arg->mountflags;
if (mkdir_flag) {
err = lntd_dir_create(0, LNTD_KO_CWD, dir, 0U,
S_IRWXU);
if (err != 0) {
return err;
}
} else if (touch_flag) {
/* Disgusting */
char *xx = dir;
if ('/' == *xx)
++xx;
for (;;) {
xx = strchr(xx, '/');
if (0 == xx)
break;
*xx = '\0';
err = lntd_dir_create(0, LNTD_KO_CWD,
dir, 0U, S_IRWXU);
if (EEXIST == err)
err = 0;
if (err != 0)
return err;
*xx = '/';
++xx;
}
err = lntd_file_create(0, LNTD_KO_CWD, dir, 0U,
S_IRWXU);
if (err != 0)
return err;
}
if (nomount_flag)
continue;
unsigned long aliasflags =
mountflags & (MS_BIND | MS_SHARED | MS_SLAVE);
if (0 == aliasflags) {
if (-1 == mount(fsname, dir, type, mountflags,
data)) {
err = errno;
return err;
}
continue;
}
if (-1 == mount(fsname, dir, type, aliasflags, 0)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
if (0 == data && 0 == (mountflags & ~aliasflags))
continue;
if (-1 == mount(fsname, dir, type,
MS_REMOUNT | mountflags, data)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
}
/* Magic incantation that clears up /proc/mounts more than
* mount MS_MOVE
*/
int old_root = open("/", O_DIRECTORY | O_CLOEXEC);
if (-1 == old_root)
return errno;
if (-1 == my_pivot_root(".", "."))
return errno;
/* pivot_root() may or may not affect its current working
* directory. It is therefore recommended to call chdir("/")
* immediately after pivot_root().
*
* - http://man7.org/linux/man-pages/man2/pivot_root.2.html
*/
if (-1 == fchdir(old_root))
return errno;
err = lntd_ko_close(old_root);
if (err != 0)
return err;
if (-1 == umount2(".", MNT_DETACH))
return errno;
if (-1 == chdir("/"))
return errno;
return 0;
}
enum { MKDIR,
TOUCH,
NOMOUNT,
SHARED,
SLAVE,
BIND,
RBIND,
RO,
RW,
SUID,
NOSUID,
NODEV,
NOEXEC };
static char const *const mount_options[] =
{[MKDIR] = "mkdir", /**/
[TOUCH] = "touch", /**/
[NOMOUNT] = "nomount", /**/
[SHARED] = "shared", /**/
[SLAVE] = "slave", /**/
[BIND] = "bind", /**/
[RBIND] = "rbind", /**/
[RO] = MNTOPT_RO, /**/
[RW] = MNTOPT_RW, /**/
[SUID] = MNTOPT_SUID, /**/
[NOSUID] = MNTOPT_NOSUID, /**/
[NODEV] = "nodev", /**/
[NOEXEC] = "noexec", /**/
0};
static lntd_error parse_mount_opts(char const *opts, bool *mkdir_flagp,
bool *touch_flagp,
bool *nomount_flagp,
unsigned long *mountflagsp,
char const **leftoversp)
{
lntd_error err;
bool nomount_flag = false;
bool touch_flag = false;
bool mkdir_flag = false;
bool shared = false;
bool slave = false;
bool bind = false;
bool rec = false;
bool readonly = false;
bool readwrite = false;
bool suid = true;
bool dev = true;
bool exec = true;
char *leftovers = 0;
char *subopts_str;
{
char *xx;
err = lntd_str_dup(&xx, opts);
if (err != 0)
return err;
subopts_str = xx;
}
char *subopts = subopts_str;
char *value = 0;
while (*subopts != '\0') {
int token;
{
char *xx = subopts;
char *yy = value;
token = getsubopt(
&xx, (char *const *)mount_options, &yy);
subopts = xx;
value = yy;
}
switch (token) {
case MKDIR:
mkdir_flag = true;
break;
case TOUCH:
touch_flag = true;
break;
case NOMOUNT:
nomount_flag = true;
break;
case SHARED:
shared = true;
break;
case SLAVE:
slave = true;
break;
case BIND:
bind = true;
break;
case RBIND:
bind = true;
rec = true;
break;
case RO:
readonly = true;
break;
case RW:
readwrite = true;
break;
case SUID:
suid = true;
break;
case NOSUID:
suid = false;
break;
case NODEV:
dev = false;
break;
case NOEXEC:
exec = false;
break;
default:
leftovers = strstr(opts, value);
goto free_subopts_str;
}
}
free_subopts_str:
lntd_mem_free(subopts_str);
if (readwrite && readonly)
return EINVAL;
/*
* Due to a completely idiotic kernel bug (see
* https://bugzilla.kernel.org/show_bug.cgi?id=24912) using a
*recursive
* bind mount as readonly would fail completely silently and
*there is
* no way to workaround this.
*
* Even after working around by remounting it will fail for the
* recursive case. For example, /home directory that is
*recursively
* bind mounted as readonly and that has encrypted user
*directories as
* an example. The /home directory will be readonly but the user
* directory /home/user will not be.
*/
if (bind && (rec || shared || slave) &&
(readonly || !suid || !dev || !exec))
return EINVAL;
if (mkdir_flag && touch_flag)
return EINVAL;
if (nomount_flag && bind)
return EINVAL;
unsigned long mountflags = 0U;
if (shared)
mountflags |= MS_SHARED;
if (slave)
mountflags |= MS_SLAVE;
if (bind)
mountflags |= MS_BIND;
if (rec)
mountflags |= MS_REC;
if (readonly)
mountflags |= MS_RDONLY;
if (!suid)
mountflags |= MS_NOSUID;
if (!dev)
mountflags |= MS_NODEV;
if (!exec)
mountflags |= MS_NOEXEC;
*leftoversp = leftovers;
*mkdir_flagp = mkdir_flag;
*touch_flagp = touch_flag;
*nomount_flagp = nomount_flag;
*mountflagsp = mountflags;
return 0;
}
LNTD_NO_SANITIZE_ADDRESS static lntd_error set_child_subreaper(bool v)
{
lntd_error err;
if (-1 == prctl(PR_SET_CHILD_SUBREAPER, (unsigned long)v, 0UL,
0UL, 0UL)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
static lntd_error safe_dup2(int oldfd, int newfd)
{
lntd_error err;
/*
* The state of a file descriptor after close gives an EINTR
* error is unspecified by POSIX so this function avoids the
* problem by simply blocking all signals.
*/
sigset_t sigset;
/* First use the signal set for the full set */
sigfillset(&sigset);
/* Then reuse the signal set for the old set */
err = pthread_sigmask(SIG_BLOCK, &sigset, &sigset);
if (err != 0)
return err;
if (-1 == dup2(oldfd, newfd)) {
err = errno;
LNTD_ASSUME(err != 0);
} else {
err = 0;
}
lntd_error mask_err = pthread_sigmask(SIG_SETMASK, &sigset, 0);
if (0 == err)
err = mask_err;
return err;
}
/* Most compilers can't handle the weirdness of vfork so contain it in
* a safe abstraction.
*/
LNTD_NOINLINE LNTD_NOCLONE LNTD_NO_SANITIZE_ADDRESS static pid_t
safe_vfork(int (*volatile f)(void *), void *volatile arg)
{
pid_t child = vfork();
if (0 == child)
_Exit(f(arg));
return child;
}
LNTD_NO_SANITIZE_ADDRESS static int my_pivot_root(char const *new_root,
char const *put_old)
{
return syscall(__NR_pivot_root, new_root, put_old);
}
static lntd_error parse_int(char const *str, int *resultp)
{
lntd_error err = 0;
char start = str[0U];
if (isspace(start))
return EINVAL;
if ('+' == start)
return EINVAL;
if ('-' == start)
return ERANGE;
errno = 0;
long yy;
char *endptr;
{
char *xx;
yy = strtol(str, &xx, 10);
endptr = xx;
}
err = errno;
if (err != 0)
return err;
if (*endptr != '\0')
return EINVAL;
if (yy > INT_MAX)
return ERANGE;
*resultp = yy;
return 0;
}
static lntd_error do_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport)
{
lntd_error err;
err = lntd_io_write_string(ko, 0, "Usage: ");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, process_name);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, " [OPTIONS]\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "Play the game.\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\
--help display this help and exit\n\
--version display version information and exit\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "Report bugs to <");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_bugreport);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ">\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_name);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, " home page: <");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_url);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ">\n");
if (err != 0)
return err;
return 0;
}
|
mstewartgallus/linted | docs/setup.h | /* Copyright (C) 2016 <NAME>
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty provided
* the copyright notice and this notice are preserved.
*/
/**
*
* @file
*
* Linted -- Process Setup
*
* First the process should open standard handles.
*
* The logger should be initialized as soon as possible.
*
* Second the process should figure out its name whether by
* commandline argument or environment variable.
*
* Signals need to be setup.
*
* The locale needs to be initialized.
*
* Privilege should be checked. The process shouldn't run at high
* privilege.
*
* Next the process should fork off the main thread and then exit it
* or send it into a loop.
*
* Next the process should sanitize file descriptors.
*/
|
mstewartgallus/linted | include/lntd/error-windows.h | <filename>include/lntd/error-windows.h
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ERROR_H
#error this header should never be included directly
#endif
/* IWYU pragma: private, include "lntd/error.h" */
#include <stdint.h>
#include <ntdef.h>
#include <winerror.h>
/* HRESULTs are 32-bit signed integers */
typedef int_fast32_t lntd_error;
#define LNTD_ERROR_AGAIN __HRESULT_FROM_WIN32(WSAEWOULDBLOCK)
#define LNTD_ERROR_CANCELLED \
__HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED)
#define LNTD_ERROR_INVALID_KO __HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE)
#define LNTD_ERROR_INVALID_PARAMETER \
__HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER)
#define LNTD_ERROR_UNIMPLEMENTED \
__HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER)
#define LNTD_ERROR_OUT_OF_MEMORY \
__HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY)
#define LNTD_ERROR_PERMISSION __HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED)
#define LNTD_ERROR_FILE_NOT_FOUND \
__HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
|
mstewartgallus/linted | src/gpu/gpu.c | <filename>src/gpu/gpu.c
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200112L
#include "config.h"
#include "lntd/assets.h"
#include "lntd/error.h"
#include "lntd/gpu.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/proc.h"
#include "lntd/sched.h"
#include "lntd/util.h"
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
struct config_attr {
EGLint renderable_type;
EGLint depth_size;
EGLint red_size;
EGLint green_size;
EGLint blue_size;
EGLint sample_buffers;
EGLint samples;
};
struct command_queue {
pthread_mutex_t lock;
pthread_cond_t wake_up;
struct lntd_gpu_update update;
uint64_t skipped_updates_counter;
lntd_gpu_x11_window window;
unsigned width;
unsigned height;
bool shown : 1U;
bool time_to_quit : 1U;
bool has_new_window : 1U;
bool remove_window : 1U;
bool update_pending : 1U;
bool resize_pending : 1U;
bool view_update_pending : 1U;
};
struct gl {
PFNGLGETERRORPROC GetError;
PFNGLINVALIDATEFRAMEBUFFERPROC InvalidateFramebuffer;
PFNGLCLEARPROC Clear;
PFNGLHINTPROC Hint;
PFNGLDISABLEPROC Disable;
PFNGLENABLEPROC Enable;
PFNGLCREATEPROGRAMPROC CreateProgram;
PFNGLCREATESHADERPROC CreateShader;
PFNGLATTACHSHADERPROC AttachShader;
PFNGLDELETESHADERPROC DeleteShader;
PFNGLSHADERSOURCEPROC ShaderSource;
PFNGLCOMPILESHADERPROC CompileShader;
PFNGLGETSHADERIVPROC GetShaderiv;
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
PFNGLLINKPROGRAMPROC LinkProgram;
PFNGLVALIDATEPROGRAMPROC ValidateProgram;
PFNGLGETPROGRAMIVPROC GetProgramiv;
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
PFNGLGENBUFFERSPROC GenBuffers;
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
PFNGLBINDBUFFERPROC BindBuffer;
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
PFNGLBUFFERDATAPROC BufferData;
PFNGLUSEPROGRAMPROC UseProgram;
PFNGLRELEASESHADERCOMPILERPROC ReleaseShaderCompiler;
PFNGLCLEARCOLORPROC ClearColor;
PFNGLDELETEBUFFERSPROC DeleteBuffers;
PFNGLDELETEPROGRAMPROC DeleteProgram;
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
PFNGLVIEWPORTPROC Viewport;
PFNGLUNIFORM3FPROC Uniform3f;
PFNGLDRAWELEMENTSPROC DrawElements;
};
struct privates {
struct gl gl;
struct lntd_gpu_update update;
struct timespec last_time;
EGLSurface surface;
EGLContext context;
EGLDisplay display;
EGLConfig config;
lntd_gpu_x11_window window;
unsigned width;
unsigned height;
GLuint program;
GLuint vertex_buffer;
GLuint normal_buffer;
GLuint index_buffer;
GLint model_view_projection_matrix;
GLint eye_vertex;
bool has_egl_surface : 1U;
bool has_egl_context : 1U;
bool has_window : 1U;
bool update_pending : 1U;
bool resize_pending : 1U;
bool has_current_context : 1U;
bool has_setup_gl : 1U;
};
struct lntd_gpu_context {
struct command_queue command_queue;
char __padding1[64U - sizeof(struct command_queue) % 64U];
struct privates privates;
pthread_t thread;
EGLDisplay display;
EGLConfig config;
};
union chunk {
GLfloat x[4U];
long double __force_alignment;
};
struct matrix {
union chunk x[4U];
};
static EGLint const attr_list[] = {
/**/ EGL_CONFORMANT, EGL_OPENGL_ES3_BIT_KHR,
/**/ EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR,
// /**/ EGL_CONTEXT_FLAGS_KHR, EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR,
/**/ EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
/**/ EGL_DEPTH_SIZE, 1, EGL_NONE};
static EGLint const context_attr[] = {EGL_CONTEXT_CLIENT_VERSION,
3, /**/
EGL_NONE};
static EGLBoolean get_egl_config_attr(struct config_attr *attr,
EGLDisplay display,
EGLConfig config);
static void *gpu_routine(void *);
static lntd_error remove_current_context(struct privates *privates);
static lntd_error destroy_egl_context(struct privates *privates,
struct gl const *restrict gl);
static lntd_error destroy_egl_surface(struct privates *privates,
struct gl const *restrict gl);
static lntd_error create_egl_context(struct privates *privates);
static lntd_error create_egl_surface(struct privates *privates);
static lntd_error make_current(struct privates *privates);
static lntd_error setup_gl(struct privates *privates,
struct gl *restrict gl);
static lntd_error destroy_gl(struct privates *privates,
struct gl const *restrict gl);
static void real_draw(struct privates *privates,
struct gl const *restrict gl);
static void flush_gl_errors(struct privates *privates,
struct gl const *restrict gl);
static inline void model_view_projection(
struct matrix *restrict resultp, GLfloat x_rotation,
GLfloat z_rotation, GLfloat x_position, GLfloat y_position,
GLfloat z_position, GLfloat mx_position, GLfloat my_position,
GLfloat mz_position, unsigned width, unsigned height);
static void matrix_multiply(struct matrix const *restrict a,
struct matrix const *restrict b,
struct matrix *restrict result);
static lntd_error get_gl_error(struct privates *privates,
struct gl const *restrict gl);
lntd_error
lntd_gpu_context_create(struct lntd_gpu_context **gpu_contextp)
{
lntd_error err = 0;
struct lntd_gpu_context *gpu_context;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *gpu_context);
if (err != 0)
return err;
gpu_context = xx;
}
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (EGL_NO_DISPLAY == display) {
EGLint err_egl = eglGetError();
switch (err_egl) {
/* In this case no display was found. */
case EGL_SUCCESS:
err = LNTD_ERROR_INVALID_PARAMETER;
break;
case EGL_BAD_ALLOC:
err = LNTD_ERROR_OUT_OF_MEMORY;
break;
default:
LNTD_ASSERT(false);
}
goto release_thread;
}
EGLint major;
EGLint minor;
{
EGLint xx;
EGLint yy;
if (EGL_FALSE == eglInitialize(display, &xx, &yy)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
/* Shouldn't happen */
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
switch (err_egl) {
case EGL_NOT_INITIALIZED:
case EGL_BAD_ALLOC:
err = LNTD_ERROR_OUT_OF_MEMORY;
goto destroy_display;
}
LNTD_ASSERT(false);
}
major = xx;
minor = yy;
}
if (1 == major && minor < 4) {
err = ENOSYS;
goto destroy_display;
}
bool egl_khr_create_context = false;
bool egl_khr_get_all_proc_addresses = false;
char const *exts = eglQueryString(display, EGL_EXTENSIONS);
for (;;) {
char const *end = strchr(exts, ' ');
if (0 == end) {
end = exts + strlen(exts);
}
size_t dist_to_end = end - exts;
if (0 == strncmp("EGL_KHR_create_context", exts,
dist_to_end)) {
egl_khr_create_context = true;
}
if (0 == strncmp("EGL_KHR_get_all_proc_addresses", exts,
dist_to_end)) {
egl_khr_get_all_proc_addresses = true;
}
if ('\0' == *end)
break;
exts = end + 1U;
}
if (!egl_khr_create_context &&
!egl_khr_get_all_proc_addresses) {
err = LNTD_ERROR_UNIMPLEMENTED;
goto destroy_display;
}
size_t matching_config_count;
{
EGLint xx;
if (EGL_FALSE ==
eglChooseConfig(display, attr_list, 0, 0, &xx)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_ATTRIBUTE);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
LNTD_ASSERT(err_egl != EGL_BAD_PARAMETER);
switch (err_egl) {
case EGL_BAD_ALLOC:
err = LNTD_ERROR_OUT_OF_MEMORY;
goto destroy_display;
}
LNTD_ASSERT(false);
}
matching_config_count = xx;
}
if (matching_config_count < 1U) {
err = LNTD_ERROR_INVALID_PARAMETER;
goto destroy_display;
}
EGLConfig *configs;
{
void *xx;
err = lntd_mem_alloc_array(&xx, matching_config_count,
sizeof configs[0U]);
if (err != 0)
goto destroy_display;
configs = xx;
}
{
EGLint xx;
if (EGL_FALSE ==
eglChooseConfig(display, attr_list, configs,
matching_config_count, &xx)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_ATTRIBUTE);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
LNTD_ASSERT(err_egl != EGL_BAD_PARAMETER);
switch (err_egl) {
case EGL_BAD_ALLOC:
err = LNTD_ERROR_OUT_OF_MEMORY;
goto free_configs;
}
LNTD_ASSERT(false);
}
LNTD_ASSERT(matching_config_count == (size_t)xx);
}
EGLConfig config;
bool got_config = false;
{
struct config_attr attr;
for (size_t ii = 0U; ii < matching_config_count; ++ii) {
EGLConfig maybe_config = configs[ii];
struct config_attr maybe_attr;
get_egl_config_attr(&maybe_attr, display,
maybe_config);
if (!((maybe_attr.renderable_type &
EGL_OPENGL_ES3_BIT_KHR) != 0))
continue;
if (!got_config)
goto choose_config;
if (maybe_attr.samples > attr.samples)
goto choose_config;
if (maybe_attr.sample_buffers >
attr.sample_buffers)
goto choose_config;
continue;
choose_config:
attr = maybe_attr;
config = maybe_config;
got_config = true;
}
}
free_configs:
lntd_mem_free(configs);
if (err != 0)
goto destroy_display;
if (!got_config) {
err = LNTD_ERROR_UNIMPLEMENTED;
goto destroy_display;
}
{
struct privates *xx = &gpu_context->privates;
memset(xx, 0, sizeof *xx);
xx->display = display;
xx->config = config;
xx->surface = EGL_NO_SURFACE;
xx->width = 1U;
xx->height = 1U;
xx->resize_pending = true;
}
{
struct command_queue *xx = &gpu_context->command_queue;
memset(xx, 0, sizeof *xx);
pthread_mutex_init(&xx->lock, 0);
pthread_cond_init(&xx->wake_up, 0);
}
err = pthread_create(&gpu_context->thread, 0, gpu_routine,
&gpu_context->command_queue);
if (err != 0)
goto destroy_display;
gpu_context->display = display;
gpu_context->config = config;
*gpu_contextp = gpu_context;
return 0;
destroy_display:
if (EGL_FALSE == eglTerminate(display)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(false);
}
release_thread:
if (EGL_FALSE == eglReleaseThread()) {
/* There are no given conditions in the standard this
* is possible for and to my knowledge no
* implementation gives special conditions for this to
* happen.
*/
LNTD_ASSERT(false);
}
lntd_mem_free(gpu_context);
LNTD_ASSERT(err != 0);
return err;
}
lntd_error
lntd_gpu_context_destroy(struct lntd_gpu_context *gpu_context)
{
lntd_error err = 0;
struct command_queue *command_queue =
&gpu_context->command_queue;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->time_to_quit = true;
pthread_cond_signal(&command_queue->wake_up);
pthread_mutex_unlock(&command_queue->lock);
}
pthread_join(gpu_context->thread, 0);
return err;
}
lntd_error lntd_gpu_set_x11_window(struct lntd_gpu_context *gpu_context,
lntd_gpu_x11_window new_window)
{
if (new_window > UINT32_MAX)
return LNTD_ERROR_INVALID_PARAMETER;
struct command_queue *command_queue =
&gpu_context->command_queue;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->remove_window = false;
command_queue->has_new_window = true;
command_queue->window = new_window;
pthread_cond_signal(&command_queue->wake_up);
pthread_mutex_unlock(&command_queue->lock);
}
return 0;
}
lntd_error lntd_gpu_remove_window(struct lntd_gpu_context *gpu_context)
{
struct command_queue *command_queue =
&gpu_context->command_queue;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->remove_window = true;
pthread_mutex_unlock(&command_queue->lock);
}
return 0;
}
void lntd_gpu_update_state(struct lntd_gpu_context *gpu_context,
struct lntd_gpu_update const *updatep)
{
struct command_queue *command_queue =
&gpu_context->command_queue;
struct lntd_gpu_update update = *updatep;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->update = update;
command_queue->update_pending = true;
++command_queue->skipped_updates_counter;
pthread_mutex_unlock(&command_queue->lock);
}
}
void lntd_gpu_resize(struct lntd_gpu_context *gpu_context,
unsigned width, unsigned height)
{
struct command_queue *command_queue =
&gpu_context->command_queue;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->width = width;
command_queue->height = height;
command_queue->resize_pending = true;
pthread_mutex_unlock(&command_queue->lock);
}
}
void lntd_gpu_hide(struct lntd_gpu_context *gpu_context)
{
struct command_queue *command_queue =
&gpu_context->command_queue;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->shown = false;
command_queue->view_update_pending = true;
pthread_mutex_unlock(&command_queue->lock);
}
}
void lntd_gpu_show(struct lntd_gpu_context *gpu_context)
{
struct command_queue *command_queue =
&gpu_context->command_queue;
{
pthread_mutex_lock(&command_queue->lock);
command_queue->shown = true;
command_queue->view_update_pending = true;
pthread_cond_signal(&command_queue->wake_up);
pthread_mutex_unlock(&command_queue->lock);
}
}
static struct timespec timespec_subtract(struct timespec x,
struct timespec y)
{
struct timespec result = {0};
long const second = 1000000000;
if (x.tv_nsec < y.tv_nsec) {
long nsec = (y.tv_nsec - x.tv_nsec) / second + 1;
y.tv_nsec -= second * nsec;
y.tv_sec += nsec;
}
if (x.tv_nsec - y.tv_nsec > second) {
long nsec = (x.tv_nsec - y.tv_nsec) / second;
y.tv_nsec += second * nsec;
y.tv_sec -= nsec;
}
result.tv_sec = x.tv_sec - y.tv_sec;
result.tv_nsec = x.tv_nsec - y.tv_nsec;
return result;
}
static void *gpu_routine(void *arg)
{
lntd_error err = 0;
lntd_proc_name("gpu-renderer");
struct lntd_gpu_context *gpu_context = arg;
struct command_queue *command_queue =
&gpu_context->command_queue;
struct privates *privates = &gpu_context->privates;
struct gl *gl = &privates->gl;
struct timespec last_time = {0};
for (;;) {
uint64_t skipped_updates_counter = 0U;
{
lntd_gpu_x11_window new_window;
struct lntd_gpu_update update;
unsigned width;
unsigned height;
bool shown = true;
bool time_to_quit = false;
bool has_new_window = false;
bool update_pending = false;
bool resize_pending = false;
bool view_update_pending = false;
bool remove_window;
pthread_mutex_lock(&command_queue->lock);
for (;;) {
time_to_quit =
command_queue->time_to_quit;
has_new_window =
command_queue->has_new_window;
remove_window =
command_queue->remove_window;
update_pending =
command_queue->update_pending;
resize_pending =
command_queue->resize_pending;
view_update_pending =
command_queue->view_update_pending;
if (has_new_window)
new_window =
command_queue->window;
if (update_pending) {
update = command_queue->update;
skipped_updates_counter =
command_queue
->skipped_updates_counter;
}
if (resize_pending) {
width = command_queue->width;
height = command_queue->height;
}
if (view_update_pending) {
shown = command_queue->shown;
}
command_queue->skipped_updates_counter =
0U;
command_queue->time_to_quit = false;
command_queue->has_new_window = false;
command_queue->remove_window = false;
command_queue->update_pending = false;
command_queue->resize_pending = false;
command_queue->view_update_pending =
false;
if (!shown && !time_to_quit) {
pthread_cond_wait(
&command_queue->wake_up,
&command_queue->lock);
continue;
}
break;
}
pthread_mutex_unlock(&command_queue->lock);
if (time_to_quit)
break;
if (remove_window) {
destroy_egl_context(privates, gl);
privates->has_window = false;
}
if (has_new_window) {
destroy_egl_context(privates, gl);
privates->window = new_window;
privates->has_window = true;
}
if (update_pending) {
privates->update = update;
privates->update_pending = true;
}
if (resize_pending) {
privates->width = width;
privates->height = height;
privates->resize_pending = true;
}
}
err = setup_gl(privates, gl);
if (err != 0) {
sched_yield();
continue;
}
real_draw(privates, gl);
{
GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
gl->InvalidateFramebuffer(
GL_FRAMEBUFFER,
LNTD_ARRAY_SIZE(attachments), attachments);
}
if (EGL_FALSE == eglSwapBuffers(privates->display,
privates->surface)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
/* Shouldn't Happen */
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_SURFACE);
LNTD_ASSERT(err_egl != EGL_BAD_CONTEXT);
LNTD_ASSERT(err_egl != EGL_BAD_MATCH);
LNTD_ASSERT(err_egl != EGL_BAD_ACCESS);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
LNTD_ASSERT(err_egl != EGL_BAD_CURRENT_SURFACE);
/* Maybe the current surface or context can
* become invalidated somehow? */
switch (err_egl) {
case EGL_BAD_NATIVE_PIXMAP:
case EGL_BAD_NATIVE_WINDOW:
case EGL_CONTEXT_LOST:
destroy_egl_context(privates, gl);
continue;
case EGL_BAD_ALLOC:
abort();
}
LNTD_ASSERT(false);
}
{
GLenum attachments[] = {GL_COLOR, GL_DEPTH,
GL_STENCIL};
gl->InvalidateFramebuffer(
GL_FRAMEBUFFER,
LNTD_ARRAY_SIZE(attachments), attachments);
}
if (0) {
if (skipped_updates_counter > 2U)
lntd_log(LNTD_LOG_INFO,
"skipped updates: %" PRIu64,
skipped_updates_counter);
}
if (0) {
struct timespec now;
lntd_sched_time(&now);
struct timespec diff =
timespec_subtract(now, last_time);
long const second = 1000000000;
double nanoseconds =
diff.tv_sec * second + diff.tv_nsec;
if (nanoseconds <= 0.0)
nanoseconds = 1.0;
lntd_log(LNTD_LOG_INFO, "FPS: %lf, SPF: %lf",
second / (double)nanoseconds,
nanoseconds / (double)second);
last_time = now;
}
}
destroy_egl_context(privates, gl);
return 0;
}
static lntd_error destroy_gl(struct privates *privates,
struct gl const *restrict gl)
{
if (!privates->has_setup_gl)
return 0;
privates->has_setup_gl = false;
GLuint vertex_buffer = privates->vertex_buffer;
GLuint normal_buffer = privates->normal_buffer;
GLuint index_buffer = privates->index_buffer;
GLuint program = privates->program;
gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
{
GLuint xx[] = {vertex_buffer, normal_buffer,
index_buffer};
gl->DeleteBuffers(LNTD_ARRAY_SIZE(xx), xx);
}
gl->UseProgram(0);
gl->DeleteProgram(program);
return 0;
}
static lntd_error remove_current_context(struct privates *privates)
{
if (!privates->has_current_context)
return 0;
privates->has_current_context = false;
lntd_error err = 0;
EGLDisplay display = privates->display;
if (EGL_FALSE == eglMakeCurrent(display, EGL_NO_SURFACE,
EGL_NO_SURFACE,
EGL_NO_CONTEXT)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
/* Shouldn't Happen */
LNTD_ASSERT(err_egl != EGL_BAD_ACCESS);
LNTD_ASSERT(err_egl != EGL_BAD_CONTEXT);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_MATCH);
LNTD_ASSERT(err_egl != EGL_BAD_PARAMETER);
LNTD_ASSERT(err_egl != EGL_BAD_SURFACE);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
/* Don't Apply */
LNTD_ASSERT(err_egl != EGL_BAD_CURRENT_SURFACE);
LNTD_ASSERT(err_egl != EGL_BAD_CONFIG);
switch (err_egl) {
default:
LNTD_ASSERT(false);
/* Maybe the current surface or context can
* become invalidated somehow? */
case EGL_CONTEXT_LOST:
case EGL_BAD_NATIVE_PIXMAP:
case EGL_BAD_NATIVE_WINDOW:
if (0 == err)
err = LNTD_ERROR_INVALID_PARAMETER;
break;
case EGL_BAD_ALLOC:
if (0 == err)
err = LNTD_ERROR_OUT_OF_MEMORY;
break;
}
}
return err;
}
static lntd_error destroy_egl_surface(struct privates *privates,
struct gl const *restrict gl)
{
destroy_gl(privates, gl);
remove_current_context(privates);
if (!privates->has_egl_surface)
return 0;
privates->has_egl_surface = false;
EGLDisplay display = privates->display;
EGLSurface surface = privates->surface;
if (EGL_FALSE == eglDestroySurface(display, surface)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_SURFACE);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
LNTD_ASSERT(false);
}
return 0;
}
static lntd_error destroy_egl_context(struct privates *privates,
struct gl const *restrict gl)
{
destroy_gl(privates, gl);
destroy_egl_surface(privates, gl);
remove_current_context(privates);
if (!privates->has_egl_context)
return 0;
privates->has_egl_context = false;
EGLDisplay display = privates->display;
EGLContext context = privates->context;
if (EGL_FALSE == eglDestroyContext(display, context)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_CONTEXT);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
LNTD_ASSERT(false);
}
return 0;
}
static lntd_error create_egl_context(struct privates *privates)
{
if (privates->has_egl_context)
return 0;
EGLDisplay display = privates->display;
EGLConfig config = privates->config;
EGLContext context = eglCreateContext(
display, config, EGL_NO_CONTEXT, context_attr);
if (EGL_NO_CONTEXT == context) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
/* Shouldn't Happen */
LNTD_ASSERT(err_egl != EGL_BAD_ACCESS);
LNTD_ASSERT(err_egl != EGL_BAD_ATTRIBUTE);
LNTD_ASSERT(err_egl != EGL_BAD_CONFIG);
LNTD_ASSERT(err_egl != EGL_BAD_CONTEXT);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_MATCH);
LNTD_ASSERT(err_egl != EGL_BAD_PARAMETER);
LNTD_ASSERT(err_egl != EGL_BAD_SURFACE);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
switch (err_egl) {
case EGL_BAD_ALLOC:
return LNTD_ERROR_OUT_OF_MEMORY;
}
LNTD_ASSERT(false);
}
privates->context = context;
privates->has_egl_context = true;
return 0;
}
static lntd_error create_egl_surface(struct privates *privates)
{
if (privates->has_egl_surface)
return 0;
if (!privates->has_window)
return LNTD_ERROR_INVALID_PARAMETER;
EGLDisplay display = privates->display;
EGLConfig config = privates->config;
lntd_gpu_x11_window window = privates->window;
EGLSurface surface =
eglCreateWindowSurface(display, config, window, 0);
if (EGL_NO_SURFACE == surface) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
LNTD_ASSERT(err_egl != EGL_BAD_ATTRIBUTE);
LNTD_ASSERT(err_egl != EGL_BAD_CONFIG);
LNTD_ASSERT(err_egl != EGL_BAD_MATCH);
switch (err_egl) {
case EGL_BAD_NATIVE_WINDOW:
return LNTD_ERROR_INVALID_PARAMETER;
case EGL_BAD_ALLOC:
return LNTD_ERROR_OUT_OF_MEMORY;
}
LNTD_ASSERT(false);
}
privates->surface = surface;
privates->has_egl_surface = true;
return 0;
}
static lntd_error make_current(struct privates *privates)
{
if (privates->has_current_context)
return 0;
lntd_error err = 0;
err = create_egl_context(privates);
if (err != 0)
return err;
err = create_egl_surface(privates);
if (err != 0)
return err;
EGLDisplay display = privates->display;
EGLSurface surface = privates->surface;
EGLContext context = privates->context;
if (EGL_FALSE ==
eglMakeCurrent(display, surface, surface, context)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
/* Shouldn't Happen */
LNTD_ASSERT(err_egl != EGL_BAD_ACCESS);
LNTD_ASSERT(err_egl != EGL_BAD_CONTEXT);
LNTD_ASSERT(err_egl != EGL_BAD_DISPLAY);
LNTD_ASSERT(err_egl != EGL_BAD_MATCH);
LNTD_ASSERT(err_egl != EGL_BAD_PARAMETER);
LNTD_ASSERT(err_egl != EGL_BAD_SURFACE);
LNTD_ASSERT(err_egl != EGL_NOT_INITIALIZED);
/* Don't Apply */
LNTD_ASSERT(err_egl != EGL_BAD_CURRENT_SURFACE);
LNTD_ASSERT(err_egl != EGL_BAD_CONFIG);
switch (err_egl) {
default:
LNTD_ASSERT(false);
/* Maybe the current surface or context can
* become invalidated somehow? */
case EGL_CONTEXT_LOST:
case EGL_BAD_NATIVE_PIXMAP:
case EGL_BAD_NATIVE_WINDOW:
if (0 == err)
err = LNTD_ERROR_INVALID_PARAMETER;
break;
case EGL_BAD_ALLOC:
if (0 == err)
err = LNTD_ERROR_OUT_OF_MEMORY;
break;
}
}
if (err != 0)
return err;
if (EGL_FALSE == eglSwapInterval(display, 1)) {
EGLint err_egl = eglGetError();
LNTD_ASSUME(err_egl != EGL_SUCCESS);
switch (err_egl) {
case EGL_NOT_INITIALIZED:
case EGL_BAD_ALLOC:
err = LNTD_ERROR_OUT_OF_MEMORY;
return err;
default:
LNTD_ASSERT(false);
}
}
privates->has_current_context = true;
return 0;
}
static lntd_error setup_gl(struct privates *privates,
struct gl *restrict gl)
{
if (privates->has_setup_gl)
return 0;
lntd_error err = 0;
err = make_current(privates);
if (err != 0)
return err;
gl->GetError =
(PFNGLGETERRORPROC)eglGetProcAddress("glGetError");
gl->InvalidateFramebuffer =
(PFNGLINVALIDATEFRAMEBUFFERPROC)eglGetProcAddress(
"glInvalidateFrameBuffer");
gl->Clear = (PFNGLCLEARPROC)eglGetProcAddress("glClear");
gl->Hint = (PFNGLHINTPROC)eglGetProcAddress("glHint");
gl->Enable = (PFNGLENABLEPROC)eglGetProcAddress("glEnable");
gl->Disable = (PFNGLDISABLEPROC)eglGetProcAddress("glDisable");
gl->CreateProgram = (PFNGLCREATEPROGRAMPROC)eglGetProcAddress(
"glCreateProgram");
gl->CreateShader =
(PFNGLCREATESHADERPROC)eglGetProcAddress("glCreateShader");
gl->AttachShader =
(PFNGLATTACHSHADERPROC)eglGetProcAddress("glAttachShader");
gl->DeleteShader =
(PFNGLDELETESHADERPROC)eglGetProcAddress("glDeleteShader");
gl->ShaderSource =
(PFNGLSHADERSOURCEPROC)eglGetProcAddress("glShaderSource");
gl->CompileShader = (PFNGLCOMPILESHADERPROC)eglGetProcAddress(
"glCompileShader");
gl->GetShaderiv =
(PFNGLGETSHADERIVPROC)eglGetProcAddress("glGetShaderiv");
gl->GetShaderInfoLog =
(PFNGLGETSHADERINFOLOGPROC)eglGetProcAddress(
"glGetShaderInfoLog");
gl->LinkProgram =
(PFNGLLINKPROGRAMPROC)eglGetProcAddress("glLinkProgram");
gl->ValidateProgram =
(PFNGLVALIDATEPROGRAMPROC)eglGetProcAddress(
"glValidateProgram");
gl->GetProgramiv =
(PFNGLGETPROGRAMIVPROC)eglGetProcAddress("glGetProgramiv");
gl->GetProgramInfoLog =
(PFNGLGETPROGRAMINFOLOGPROC)eglGetProcAddress(
"glGetProgramInfoLog");
gl->GenBuffers =
(PFNGLGENBUFFERSPROC)eglGetProcAddress("glGenBuffers");
gl->GetUniformLocation =
(PFNGLGETUNIFORMLOCATIONPROC)eglGetProcAddress(
"glGetUniformLocation");
gl->GetAttribLocation =
(PFNGLGETATTRIBLOCATIONPROC)eglGetProcAddress(
"glGetAttribLocation");
gl->EnableVertexAttribArray =
(PFNGLENABLEVERTEXATTRIBARRAYPROC)eglGetProcAddress(
"glEnableVertexAttribArray");
gl->BindBuffer =
(PFNGLBINDBUFFERPROC)eglGetProcAddress("glBindBuffer");
gl->VertexAttribPointer =
(PFNGLVERTEXATTRIBPOINTERPROC)eglGetProcAddress(
"glVertexAttribPointer");
gl->BufferData =
(PFNGLBUFFERDATAPROC)eglGetProcAddress("glBufferData");
gl->UseProgram =
(PFNGLUSEPROGRAMPROC)eglGetProcAddress("glUseProgram");
gl->ReleaseShaderCompiler =
(PFNGLRELEASESHADERCOMPILERPROC)eglGetProcAddress(
"glReleaseShaderCompiler");
gl->ClearColor =
(PFNGLCLEARCOLORPROC)eglGetProcAddress("glClearColor");
gl->DeleteBuffers = (PFNGLDELETEBUFFERSPROC)eglGetProcAddress(
"glDeleteBuffers");
gl->DeleteProgram = (PFNGLDELETEPROGRAMPROC)eglGetProcAddress(
"glDeleteProgram");
gl->UniformMatrix4fv =
(PFNGLUNIFORMMATRIX4FVPROC)eglGetProcAddress(
"glUniformMatrix4fv");
gl->Viewport =
(PFNGLVIEWPORTPROC)eglGetProcAddress("glViewport");
gl->Uniform3f =
(PFNGLUNIFORM3FPROC)eglGetProcAddress("glUniform3f");
gl->DrawElements =
(PFNGLDRAWELEMENTSPROC)eglGetProcAddress("glDrawElements");
gl->Hint(GL_GENERATE_MIPMAP_HINT, GL_FASTEST);
gl->Hint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, GL_FASTEST);
gl->Enable(GL_DEPTH_TEST);
gl->Enable(GL_CULL_FACE);
/* Use the default clear color for performance */
flush_gl_errors(privates, gl);
GLuint program = gl->CreateProgram();
if (0 == program) {
return get_gl_error(privates, gl);
}
flush_gl_errors(privates, gl);
GLuint fragment_shader = gl->CreateShader(GL_FRAGMENT_SHADER);
if (0 == fragment_shader) {
err = get_gl_error(privates, gl);
goto cleanup_program;
}
gl->AttachShader(program, fragment_shader);
gl->DeleteShader(fragment_shader);
gl->ShaderSource(fragment_shader, 1U,
(GLchar const **)&lntd_assets_fragment_shader,
0);
gl->CompileShader(fragment_shader);
GLint fragment_is_valid;
{
GLint xx = false;
gl->GetShaderiv(fragment_shader, GL_COMPILE_STATUS,
&xx);
fragment_is_valid = xx;
}
if (!fragment_is_valid) {
err = LNTD_ERROR_INVALID_PARAMETER;
size_t info_log_length;
{
GLint xx = 0;
gl->GetShaderiv(fragment_shader,
GL_INFO_LOG_LENGTH, &xx);
info_log_length = xx;
}
GLchar *info_log;
{
void *xx;
lntd_error mem_err =
lntd_mem_alloc(&xx, info_log_length);
if (mem_err != 0)
goto cleanup_program;
info_log = xx;
}
gl->GetShaderInfoLog(fragment_shader, info_log_length,
0, info_log);
lntd_log(LNTD_LOG_ERROR, "invalid shader: %s",
info_log);
lntd_mem_free(info_log);
}
flush_gl_errors(privates, gl);
GLuint vertex_shader = gl->CreateShader(GL_VERTEX_SHADER);
if (0 == vertex_shader) {
err = get_gl_error(privates, gl);
goto cleanup_program;
}
gl->AttachShader(program, vertex_shader);
gl->DeleteShader(vertex_shader);
gl->ShaderSource(vertex_shader, 1U,
(GLchar const **)&lntd_assets_vertex_shader,
0);
gl->CompileShader(vertex_shader);
GLint vertex_is_valid;
{
GLint xx = false;
gl->GetShaderiv(vertex_shader, GL_COMPILE_STATUS, &xx);
vertex_is_valid = xx;
}
if (!vertex_is_valid) {
err = LNTD_ERROR_INVALID_PARAMETER;
size_t info_log_length = 0;
{
GLint xx;
gl->GetShaderiv(vertex_shader,
GL_INFO_LOG_LENGTH, &xx);
info_log_length = xx;
}
GLchar *info_log;
{
void *xx;
lntd_error mem_err =
lntd_mem_alloc(&xx, info_log_length);
if (mem_err != 0)
goto cleanup_program;
info_log = xx;
}
gl->GetShaderInfoLog(vertex_shader, info_log_length, 0,
info_log);
lntd_log(LNTD_LOG_ERROR, "invalid shader: %s",
info_log);
lntd_mem_free(info_log);
goto cleanup_program;
}
gl->LinkProgram(program);
gl->ValidateProgram(program);
GLint program_is_valid;
{
GLint xx = false;
gl->GetProgramiv(program, GL_VALIDATE_STATUS, &xx);
program_is_valid = xx;
}
if (!program_is_valid) {
err = LNTD_ERROR_INVALID_PARAMETER;
size_t info_log_length;
{
GLint xx = 0;
gl->GetProgramiv(program, GL_INFO_LOG_LENGTH,
&xx);
info_log_length = xx;
}
GLchar *info_log;
{
void *xx;
lntd_error mem_err =
lntd_mem_alloc(&xx, info_log_length);
if (mem_err != 0)
goto cleanup_program;
info_log = xx;
}
gl->GetProgramInfoLog(program, info_log_length, 0,
info_log);
lntd_log(LNTD_LOG_ERROR, "invalid program: %s",
info_log);
lntd_mem_free(info_log);
goto cleanup_program;
}
GLuint vertex_buffer;
GLuint normal_buffer;
GLuint index_buffer;
{
GLuint xx[3U];
gl->GenBuffers(LNTD_ARRAY_SIZE(xx), xx);
vertex_buffer = xx[0U];
normal_buffer = xx[1U];
index_buffer = xx[2U];
}
GLint eye_vertex =
gl->GetUniformLocation(program, "eye_vertex");
GLint mvp_matrix = gl->GetUniformLocation(
program, "model_view_projection_matrix");
GLint maybe_vertex = gl->GetAttribLocation(program, "vertex");
if (maybe_vertex < 0) {
err = LNTD_ERROR_INVALID_PARAMETER;
goto cleanup_buffers;
}
GLuint vertex = maybe_vertex;
GLint maybe_normal = gl->GetAttribLocation(program, "normal");
if (maybe_normal < 0) {
err = LNTD_ERROR_INVALID_PARAMETER;
goto cleanup_buffers;
}
GLuint normal = maybe_normal;
gl->EnableVertexAttribArray(vertex);
gl->EnableVertexAttribArray(normal);
gl->BindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
gl->VertexAttribPointer(
vertex, LNTD_ARRAY_SIZE(lntd_assets_vertices[0U]), GL_FLOAT,
false, 0, 0);
gl->BindBuffer(GL_ARRAY_BUFFER, normal_buffer);
gl->VertexAttribPointer(
normal, LNTD_ARRAY_SIZE(lntd_assets_normals[0U]), GL_FLOAT,
false, 0, 0);
gl->BindBuffer(GL_ARRAY_BUFFER, 0);
gl->BindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
gl->BufferData(GL_ARRAY_BUFFER,
lntd_assets_size *
sizeof lntd_assets_vertices[0U],
lntd_assets_vertices, GL_STATIC_DRAW);
gl->BindBuffer(GL_ARRAY_BUFFER, normal_buffer);
gl->BufferData(GL_ARRAY_BUFFER,
lntd_assets_size *
sizeof lntd_assets_normals[0U],
lntd_assets_normals, GL_STATIC_DRAW);
gl->BindBuffer(GL_ARRAY_BUFFER, 0);
gl->UseProgram(program);
gl->ReleaseShaderCompiler();
gl->ClearColor(0.94, 0.9, 1.0, 0.0);
privates->program = program;
privates->vertex_buffer = vertex_buffer;
privates->normal_buffer = normal_buffer;
privates->index_buffer = index_buffer;
privates->model_view_projection_matrix = mvp_matrix;
privates->eye_vertex = eye_vertex;
privates->update_pending = true;
privates->resize_pending = true;
privates->has_setup_gl = true;
return 0;
cleanup_buffers : {
GLuint xx[] = {vertex_buffer, normal_buffer, index_buffer};
gl->DeleteBuffers(LNTD_ARRAY_SIZE(xx), xx);
}
cleanup_program:
gl->DeleteProgram(program);
return err;
}
static void real_draw(struct privates *privates,
struct gl const *restrict gl)
{
struct lntd_gpu_update const *update = &privates->update;
unsigned width = privates->width;
unsigned height = privates->height;
bool update_pending = privates->update_pending;
bool resize_pending = privates->resize_pending;
GLint mvp_matrix = privates->model_view_projection_matrix;
GLint eye_vertex = privates->eye_vertex;
if (resize_pending) {
gl->Viewport(0, 0, width, height);
privates->resize_pending = false;
}
if (update_pending) {
GLfloat x_position = update->x_position;
GLfloat y_position = update->y_position;
GLfloat z_position = update->z_position;
if (eye_vertex >= 0)
gl->Uniform3f(eye_vertex, x_position,
y_position, z_position);
privates->update_pending = false;
}
gl->Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT);
GLuint index_buffer = privates->index_buffer;
gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
for (size_t ii = 0U; ii < lntd_assets_assets_size; ++ii) {
uint16_t start = lntd_assets_assets[ii].start;
uint16_t length = lntd_assets_assets[ii].length;
gl->BufferData(
GL_ELEMENT_ARRAY_BUFFER,
3U * length * sizeof lntd_assets_indices[0U],
lntd_assets_indices + 3U * start, GL_DYNAMIC_DRAW);
{
/* X, Y, Z, W coords of the resultant vector are
* the
* sums of the columns (row major order).
*/
GLfloat z_rotation = update->z_rotation;
GLfloat x_rotation = update->x_rotation;
GLfloat x_position = update->x_position;
GLfloat y_position = update->y_position;
GLfloat z_position = update->z_position;
GLfloat mx_position = update->mx_position;
GLfloat my_position = update->my_position;
GLfloat mz_position = update->mz_position;
if (ii != 0) {
mx_position = 0;
my_position = 0;
mz_position = 0;
}
if (mvp_matrix >= 0) {
struct matrix mvp;
model_view_projection(
&mvp, x_rotation, z_rotation,
x_position, y_position, z_position,
mx_position, my_position,
mz_position, width, height);
gl->UniformMatrix4fv(
mvp_matrix, 1U, false,
(void const *)&mvp);
}
}
gl->DrawElements(GL_TRIANGLES, 3U * length,
GL_UNSIGNED_SHORT, 0);
}
}
static void flush_gl_errors(struct privates *privates,
struct gl const *restrict gl)
{
GLenum error;
do {
error = gl->GetError();
} while (error != GL_NO_ERROR);
}
static lntd_error get_gl_error(struct privates *privates,
struct gl const *restrict gl)
{
/* Note that a single OpenGL call may return multiple errors
* so we get them all and then return the most serious.
*/
bool invalid_parameter = false;
bool out_of_memory = false;
bool unimplemented_error = false;
for (;;) {
bool exit = false;
switch (gl->GetError()) {
case GL_NO_ERROR:
exit = true;
break;
case GL_INVALID_ENUM:
case GL_INVALID_VALUE:
case GL_INVALID_OPERATION:
case GL_INVALID_FRAMEBUFFER_OPERATION:
invalid_parameter = true;
break;
case GL_OUT_OF_MEMORY:
out_of_memory = true;
break;
default:
unimplemented_error = true;
break;
}
if (exit)
break;
}
/* Prioritize the errors by how serious they are */
/* An unknown type of error, could be anything */
if (unimplemented_error)
return LNTD_ERROR_UNIMPLEMENTED;
/* Fundamental logic error, very serious */
if (invalid_parameter)
return LNTD_ERROR_INVALID_PARAMETER;
/* Runtime error */
if (out_of_memory)
return LNTD_ERROR_OUT_OF_MEMORY;
return 0;
}
static inline void model_view_projection(
struct matrix *restrict resultp, GLfloat x_rotation,
GLfloat z_rotation, GLfloat x_position, GLfloat y_position,
GLfloat z_position, GLfloat mx_position, GLfloat my_position,
GLfloat mz_position, unsigned width, unsigned height)
{
/* Rotate the camera */
GLfloat cos_x = cosf(x_rotation);
GLfloat sin_x = sinf(x_rotation);
GLfloat cos_z = cosf(z_rotation);
GLfloat sin_z = sinf(z_rotation);
double aspect = width / (double)height;
double fov = acos(-1.0) / 4;
double d = 1 / tan(fov / 2);
double far = 1000;
double near = 1;
struct matrix model_view;
{
struct matrix m;
{
struct matrix rotations;
{
struct matrix const x_rotation_matrix =
{{{1, 0, 0, 0},
{0, cos_x, -sin_x, 0},
{0, sin_x, cos_x, 0},
{0, 0, 0, 1}}};
struct matrix const z_rotation_matrix =
{{{cos_z, sin_z, 0, 0},
{-sin_z, cos_z, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}}};
matrix_multiply(&z_rotation_matrix,
&x_rotation_matrix,
&rotations);
}
struct matrix const model = {
{{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{-mx_position, -my_position, -mz_position,
1}}};
matrix_multiply(&model, &rotations, &m);
}
/* Translate the camera */
struct matrix const camera = {
{{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{x_position, y_position, z_position, 1}}};
matrix_multiply(&camera, &m, &model_view);
}
struct matrix const projection = {
{{d / aspect, 0, 0, 0},
{0, d, 0, 0},
{0, 0, (far + near) / (near - far),
2 * far * near / (near - far)},
{0, 0, -1, 0}}};
matrix_multiply(&model_view, &projection, resultp);
}
static inline void matrix_multiply(struct matrix const *restrict a,
struct matrix const *restrict b,
struct matrix *restrict result)
{
struct matrix b_inverted;
{
uint_fast8_t ii = 4U;
do {
--ii;
GLfloat b_ii_0;
GLfloat b_ii_1;
GLfloat b_ii_2;
GLfloat b_ii_3;
{
union chunk b_ii = b->x[ii];
b_ii_0 = b_ii.x[0U];
b_ii_1 = b_ii.x[1U];
b_ii_2 = b_ii.x[2U];
b_ii_3 = b_ii.x[3U];
}
char *b_inverted_XX_ii = &((
char *)&b_inverted)[ii * sizeof(GLfloat)];
*(GLfloat *)(b_inverted_XX_ii +
0U * sizeof(union chunk)) = b_ii_0;
*(GLfloat *)(b_inverted_XX_ii +
1U * sizeof(union chunk)) = b_ii_1;
*(GLfloat *)(b_inverted_XX_ii +
2U * sizeof(union chunk)) = b_ii_2;
*(GLfloat *)(b_inverted_XX_ii +
3U * sizeof(union chunk)) = b_ii_3;
} while (ii != 0U);
}
uint_fast8_t ii = 4U;
do {
--ii;
GLfloat a_ii_0;
GLfloat a_ii_1;
GLfloat a_ii_2;
GLfloat a_ii_3;
{
union chunk a_ii = a->x[ii];
a_ii_0 = a_ii.x[0U];
a_ii_1 = a_ii.x[1U];
a_ii_2 = a_ii.x[2U];
a_ii_3 = a_ii.x[3U];
}
union chunk result_ii;
uint_fast8_t jj = 4U;
do {
--jj;
GLfloat result_ii_jj;
{
GLfloat b_0_jj;
GLfloat b_1_jj;
GLfloat b_2_jj;
GLfloat b_3_jj;
{
union chunk b_XX_jj =
b_inverted.x[jj];
b_0_jj = b_XX_jj.x[0U];
b_1_jj = b_XX_jj.x[1U];
b_2_jj = b_XX_jj.x[2U];
b_3_jj = b_XX_jj.x[3U];
}
result_ii_jj =
(a_ii_0 * b_0_jj +
a_ii_1 * b_1_jj) +
(a_ii_2 * b_2_jj + a_ii_3 * b_3_jj);
}
result_ii.x[jj] = result_ii_jj;
} while (jj != 0U);
result->x[ii] = result_ii;
} while (ii != 0U);
}
static EGLBoolean get_egl_config_attr(struct config_attr *attr,
EGLDisplay display,
EGLConfig config)
{
if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE,
&attr->renderable_type))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE,
&attr->depth_size))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_RED_SIZE,
&attr->red_size))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_GREEN_SIZE,
&attr->green_size))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_BLUE_SIZE,
&attr->blue_size))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE,
&attr->depth_size))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_SAMPLES,
&attr->samples))
return EGL_FALSE;
if (!eglGetConfigAttrib(display, config, EGL_SAMPLE_BUFFERS,
&attr->sample_buffers))
return EGL_FALSE;
return EGL_TRUE;
}
|
mstewartgallus/linted | include/lntd/mem.h | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_MEM_H
#define LNTD_MEM_H
#include "lntd/error.h"
#include <stddef.h>
/**
* @file
*
* Allocates memory.
*/
/* For consistent platform behaviour we return the null pointer on
* zero sized allocations.
*/
static inline lntd_error
lntd_mem_safe_multiply(size_t nmemb, size_t size, size_t *resultp)
{
if (size > 0U && ((size_t)-1) / size < nmemb)
return LNTD_ERROR_OUT_OF_MEMORY;
*resultp = nmemb *size;
return 0;
}
static inline lntd_error lntd_mem_alloc(void **memp, size_t size)
{
extern void *malloc(size_t size);
void *memory;
if (0U == size) {
memory = 0;
} else {
memory = malloc(size);
if (0 == memory)
return LNTD_ERROR_OUT_OF_MEMORY;
}
*memp = memory;
return 0;
}
static inline lntd_error lntd_mem_alloc_array(void **memp, size_t nmemb,
size_t size)
{
extern void *malloc(size_t size);
lntd_error err;
void *memory;
size_t total;
if (0U == nmemb || 0U == size) {
memory = 0;
goto store_mem;
}
err = lntd_mem_safe_multiply(nmemb, size, &total);
if (err != 0)
return err;
memory = malloc(total);
if (0 == memory)
return LNTD_ERROR_OUT_OF_MEMORY;
store_mem:
*memp = memory;
return 0;
}
static inline lntd_error lntd_mem_alloc_zeroed(void **memp, size_t size)
{
extern void *calloc(size_t nmemb, size_t size);
void *memory;
if (0U == size) {
memory = 0;
} else {
memory = calloc(1U, size);
if (0 == memory)
return LNTD_ERROR_OUT_OF_MEMORY;
}
*memp = memory;
return 0;
}
static inline lntd_error
lntd_mem_alloc_array_zeroed(void **memp, size_t nmemb, size_t size)
{
extern void *calloc(size_t nmemb, size_t size);
void *memory;
if (0U == nmemb || 0U == size) {
memory = 0;
} else {
memory = calloc(nmemb, size);
if (0 == memory)
return LNTD_ERROR_OUT_OF_MEMORY;
}
*memp = memory;
return 0;
}
static inline lntd_error lntd_mem_realloc(void **memp, void *memory,
size_t new_size)
{
extern void *realloc(void *ptr, size_t size);
extern void free(void *ptr);
void *new_memory;
if (0U == new_size) {
free(memory);
new_memory = 0;
} else {
new_memory = realloc(memory, new_size);
if (0 == new_memory)
return LNTD_ERROR_OUT_OF_MEMORY;
}
*memp = new_memory;
return 0;
}
static inline lntd_error lntd_mem_realloc_array(void **memp,
void *memory,
size_t nmemb,
size_t size)
{
extern void *realloc(void *ptr, size_t size);
extern void free(void *ptr);
lntd_error err = 0;
void *new_memory;
size_t total;
if (0U == nmemb || 0U == size) {
free(memory);
new_memory = 0;
goto store_mem;
}
err = lntd_mem_safe_multiply(nmemb, size, &total);
if (err != 0)
return err;
new_memory = realloc(memory, total);
if (0 == new_memory)
return LNTD_ERROR_OUT_OF_MEMORY;
store_mem:
*memp = new_memory;
return 0;
}
static inline void lntd_mem_free(void *memory)
{
extern void free(void *ptr);
/* This is primarily for making debugging easier and not for
* any sort of optimization */
if (memory != 0)
free(memory);
}
#endif /* LNTD_MEM_H */
|
mstewartgallus/linted | src/unit/unit.c | <filename>src/unit/unit.c
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/proc.h"
#include "lntd/unit.h"
#include "lntd/util.h"
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
struct lntd_unit_db {
size_t size;
struct lntd_unit *list;
};
lntd_error lntd_unit_db_create(struct lntd_unit_db **unitsp)
{
lntd_error err;
struct lntd_unit_db *units;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *units);
if (err != 0)
return err;
units = xx;
}
units->size = 0U;
units->list = 0;
*unitsp = units;
return 0;
}
lntd_error lntd_unit_db_add_unit(struct lntd_unit_db *units,
struct lntd_unit **unitp)
{
lntd_error err = 0;
LNTD_ASSERT(units != 0);
LNTD_ASSERT(unitp != 0);
struct lntd_unit *list = units->list;
size_t old_size = units->size;
size_t new_size = old_size + 1U;
LNTD_ASSERT(new_size > 0U);
{
void *xx = 0;
err = lntd_mem_realloc_array(&xx, list, new_size,
sizeof list[0U]);
if (err != 0)
return err;
list = xx;
}
list[old_size].name = 0;
*unitp = &(list[old_size]);
units->list = list;
units->size = new_size;
return err;
}
void lntd_unit_db_destroy(struct lntd_unit_db *units)
{
size_t size = units->size;
struct lntd_unit *list = units->list;
for (size_t ii = 0U; ii < size; ++ii)
lntd_mem_free(list[ii].name);
lntd_mem_free(list);
lntd_mem_free(units);
}
size_t lntd_unit_db_size(struct lntd_unit_db *units)
{
return units->size;
}
struct lntd_unit *lntd_unit_db_get_unit(struct lntd_unit_db *units,
size_t ii)
{
return &units->list[ii];
}
struct lntd_unit *
lntd_unit_db_get_unit_by_name(struct lntd_unit_db *units,
char const *name)
{
size_t size = units->size;
struct lntd_unit *list = units->list;
for (size_t ii = 0U; ii < size; ++ii) {
struct lntd_unit *unit = &list[ii];
if (0 == strncmp(unit->name, name, LNTD_UNIT_NAME_MAX))
return unit;
}
return 0;
}
lntd_error lntd_unit_name(lntd_proc pid,
char name[static LNTD_UNIT_NAME_MAX + 1U])
{
lntd_error err;
memset(name, 0, LNTD_UNIT_NAME_MAX + 1U);
char path[sizeof "/proc/" - 1U +
LNTD_NUMBER_TYPE_STRING_SIZE(lntd_proc) +
sizeof "/environ" - 1U + 1U];
if (-1 == sprintf(path, "/proc/%" PRIuMAX "/environ",
(uintmax_t)pid)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
lntd_ko ko;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, path,
LNTD_KO_RDONLY);
if (LNTD_ERROR_FILE_NOT_FOUND == err)
return ESRCH;
if (err != 0)
return err;
ko = xx;
}
FILE *file = fdopen(ko, "r");
if (0 == file) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(ko);
return err;
}
/* Get the buffer all at once to avoid raciness. */
char *buf = 0;
bool eof = false;
ssize_t zz;
{
char *xx = buf;
size_t yy = 0U;
errno = 0;
zz = getline(&xx, &yy, file);
buf = xx;
}
if (-1 == zz) {
err = errno;
/* May be zero */
eof = true;
}
if (EOF == fclose(file)) {
if (0 == err) {
err = errno;
LNTD_ASSUME(err != 0);
}
}
if (err != 0)
goto free_buf;
memset(name, 0, LNTD_UNIT_NAME_MAX + 1U);
if (eof)
goto free_buf;
char *iter = buf;
for (;;) {
if (0 == strncmp("LINTED_SERVICE=", iter,
strlen("LINTED_SERVICE="))) {
strncpy(name, iter + strlen("LINTED_SERVICE="),
LNTD_UNIT_NAME_MAX);
break;
}
iter = strchr(iter, '\0');
if (0 == iter) {
err = EINVAL;
break;
}
++iter;
if ('\0' == *iter)
break;
if ('\n' == *iter)
break;
}
free_buf:
lntd_mem_free(buf);
return err;
}
lntd_error lntd_unit_pid(lntd_proc *pidp, lntd_proc manager_pid,
char const *name)
{
lntd_error err = 0;
lntd_proc *children;
size_t len;
{
lntd_proc *xx;
size_t yy;
err = lntd_proc_children(manager_pid, &xx, &yy);
if (err != 0)
return err;
children = xx;
len = yy;
}
if (0U == len)
return ESRCH;
lntd_proc child;
bool found_child = false;
for (size_t ii = 0U; ii < len; ++ii) {
child = children[ii];
char other_name[LNTD_UNIT_NAME_MAX + 1U];
err = lntd_unit_name(child, other_name);
if (EACCES == err) {
err = 0U;
continue;
}
if (err != 0)
goto free_buf;
if (0 == strcmp(name, other_name)) {
found_child = true;
break;
}
}
free_buf:
lntd_mem_free(children);
if (err != 0)
return err;
if (!found_child)
return ESRCH;
if (pidp != 0)
*pidp = child;
return 0;
}
|
mstewartgallus/linted | include/lntd/env.h | <reponame>mstewartgallus/linted
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ENV_H
#define LNTD_ENV_H
#include "lntd/error.h"
/**
* @file
*
* Manipulate a process environment.
*/
/**
* @todo Deprecated `lntd_env_set` as it is racy in multithreaded
* environments.
*/
lntd_error lntd_env_set(char const *key, char const *value,
unsigned char overwrite);
lntd_error lntd_env_get(char const *key, char **valuep);
#endif /* LNTD_ENV_H */
|
mstewartgallus/linted | include/lntd/assets.h | /*
* Copyright 2014 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ASSETS_H
#define LNTD_ASSETS_H
#include <stddef.h>
#include <stdint.h>
/**
* @file
*
* Stores asset data.
*/
typedef float lntd_assets_point[3U];
struct lntd_assets_asset {
uint16_t start;
uint16_t length;
};
extern size_t const lntd_assets_size;
extern lntd_assets_point const *const lntd_assets_vertices;
extern lntd_assets_point const *const lntd_assets_normals;
extern uint16_t const *const lntd_assets_indices;
extern size_t const lntd_assets_indices_size;
extern struct lntd_assets_asset const *const lntd_assets_assets;
extern size_t const lntd_assets_assets_size;
extern char const *const lntd_assets_fragment_shader;
extern char const *const lntd_assets_vertex_shader;
#endif /* LNTD_ASSETS_H */
|
mstewartgallus/linted | src/sched/sched-posix.c | <filename>src/sched/sched-posix.c
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200112L
#include "config.h"
#include "lntd/sched.h"
#include "lntd/async.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <sched.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <time.h>
struct lntd_sched_task_sleep_until {
struct lntd_async_task *parent;
void *data;
struct timespec time;
};
lntd_error lntd_sched_getpriority(lntd_sched_priority *priorityp)
{
errno = 0;
int priority = getpriority(PRIO_PROCESS, 0);
if (-1 == priority) {
lntd_error err = errno;
if (err != 0)
return err;
}
*priorityp = priority;
return 0;
}
lntd_error lntd_sched_time(struct timespec *now)
{
if (-1 == clock_gettime(CLOCK_MONOTONIC, now)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
/* task_idle is just a fake */
lntd_error
lntd_sched_task_idle_create(struct lntd_sched_task_idle **taskp,
void *data)
{
struct lntd_async_task *xx;
lntd_error err =
lntd_async_task_create(&xx, data, LNTD_ASYNCH_TASK_IDLE);
if (err != 0)
return err;
*taskp = (struct lntd_sched_task_idle *)xx;
return 0;
}
void lntd_sched_task_idle_destroy(struct lntd_sched_task_idle *task)
{
lntd_async_task_destroy((void *)task);
}
void *lntd_sched_task_idle_data(struct lntd_sched_task_idle *task)
{
return lntd_async_task_data((void *)task);
}
void lntd_sched_task_idle_submit(struct lntd_async_pool *pool,
struct lntd_sched_task_idle *task,
union lntd_async_ck task_ck,
void *userstate)
{
lntd_async_task_submit(pool, (void *)task, task_ck, userstate);
}
lntd_error lntd_sched_task_sleep_until_create(
struct lntd_sched_task_sleep_until **taskp, void *data)
{
lntd_error err;
struct lntd_sched_task_sleep_until *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(
&xx, task, LNTD_ASYNCH_TASK_SLEEP_UNTIL);
if (err != 0)
goto free_task;
parent = xx;
}
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_task:
lntd_mem_free(task);
return err;
}
void lntd_sched_task_sleep_until_destroy(
struct lntd_sched_task_sleep_until *task)
{
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void *lntd_sched_task_sleep_until_data(
struct lntd_sched_task_sleep_until *task)
{
return task->data;
}
void lntd_sched_task_sleep_until_time(
struct lntd_sched_task_sleep_until *task, struct timespec *xx)
{
*xx = task->time;
}
void lntd_sched_task_sleep_until_submit(
struct lntd_async_pool *pool,
struct lntd_sched_task_sleep_until *task,
union lntd_async_ck task_ck, void *userstate,
struct timespec const *xx)
{
task->time = *xx;
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
void lntd_sched_task_sleep_until_cancel(
struct lntd_sched_task_sleep_until *task)
{
lntd_async_task_cancel(task->parent);
}
void lntd_sched_do_idle(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
sched_yield();
lntd_async_pool_complete(pool, task, 0);
}
void lntd_sched_do_sleep_until(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_sched_task_sleep_until *task_sleep =
lntd_async_task_data(task);
lntd_error err = 0;
if (-1 == clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
&task_sleep->time,
&task_sleep->time)) {
err = errno;
LNTD_ASSUME(err != 0);
}
if (EINTR == err) {
lntd_async_pool_resubmit(pool, task);
return;
}
lntd_async_pool_complete(pool, task, err);
}
|
mstewartgallus/linted | include/lntd/signal.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_SIGNAL_H
#define LNTD_SIGNAL_H
#include "lntd/error.h"
/**
* @file
*
* Signal handling.
*/
struct lntd_async_pool;
struct lntd_async_task;
union lntd_async_ck;
struct lntd_signal_task_wait;
lntd_error lntd_signal_init(void);
lntd_error
lntd_signal_task_wait_create(struct lntd_signal_task_wait **taskp,
void *data);
void lntd_signal_task_wait_destroy(struct lntd_signal_task_wait *task);
void lntd_signal_task_wait_submit(struct lntd_async_pool *pool,
struct lntd_signal_task_wait *task,
union lntd_async_ck task_ck,
void *userstate);
void *lntd_signal_task_wait_data(struct lntd_signal_task_wait *task);
int lntd_signal_task_wait_signo(struct lntd_signal_task_wait *task);
void lntd_signal_task_wait_cancel(struct lntd_signal_task_wait *task);
void lntd_signal_do_wait(struct lntd_async_pool *pool,
struct lntd_async_task *task);
void lntd_signal_listen_to_sigchld(void);
void lntd_signal_listen_to_sighup(void);
void lntd_signal_listen_to_sigint(void);
void lntd_signal_listen_to_sigquit(void);
void lntd_signal_listen_to_sigterm(void);
char const *lntd_signal_string(int signo);
#endif /* LNTD_SIGNAL_H */
|
mstewartgallus/linted | src/linted-monitor/monitor-windows.c | <reponame>mstewartgallus/linted
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/error.h"
#include "lntd/log.h"
#include "lntd/start.h"
#include <stdlib.h>
#include <windows.h>
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-monitor", 0};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
for (;;) {
MSG message = {0};
if (!GetMessage(&message, 0, 0, 0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
char const *error_str = lntd_error_string(err);
lntd_log(LNTD_LOG_ERROR, "GetMessage: %s",
error_str);
lntd_error_string_free(error_str);
}
}
return EXIT_SUCCESS;
}
|
mstewartgallus/linted | src/nesc/update.h | <filename>src/nesc/update.h
/*
* Copyright 2015,2016 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_UPDATE_H
#define LNTD_UPDATE_H
nx_struct lntd_update_input
{
nx_int32_t x_position;
nx_int32_t y_position;
nx_int32_t z_position;
nx_int32_t mx_position;
nx_int32_t my_position;
nx_int32_t mz_position;
nx_uint32_t z_rotation;
nx_uint32_t x_rotation;
};
#endif /* LNTD_UPDATE_H */
|
mstewartgallus/linted | src/fifo/fifo-posix.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/error.h"
#include "lntd/fifo.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <unistd.h>
#if !defined HAVE_MKFIFOAT && defined HAVE_SYSCALL
#include <sys/syscall.h>
#endif
static lntd_error my_mkfifoat(int dir, char const *pathname,
mode_t mode);
lntd_error lntd_fifo_pair(lntd_fifo *readerp, lntd_fifo *writerp,
unsigned long flags)
{
if (flags != 0U)
return EINVAL;
int xx[2U];
if (-1 == pipe2(xx, O_CLOEXEC | O_NONBLOCK)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
*readerp = xx[0U];
*writerp = xx[1U];
return 0;
}
lntd_error lntd_fifo_create(lntd_fifo *kop, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode)
{
lntd_error err;
int fd = -1;
if (dirko > INT_MAX && dirko != LNTD_KO_CWD)
return EINVAL;
if (0 == kop) {
if (flags != 0U)
return EINVAL;
int mydirfd;
if (LNTD_KO_CWD == dirko) {
mydirfd = AT_FDCWD;
} else if (dirko > INT_MAX) {
return EINVAL;
} else {
mydirfd = dirko;
}
err = my_mkfifoat(mydirfd, pathname, mode);
if (err != 0) {
if (EEXIST == err)
return 0;
return err;
}
return 0;
}
if ((flags & ~LNTD_FIFO_ONLY & ~LNTD_FIFO_RDONLY &
~LNTD_FIFO_WRONLY & ~LNTD_FIFO_RDWR) != 0U)
return EINVAL;
bool fifo_only = (flags & LNTD_FIFO_ONLY) != 0U;
bool fifo_rdonly = (flags & LNTD_FIFO_RDONLY) != 0U;
bool fifo_wronly = (flags & LNTD_FIFO_WRONLY) != 0U;
bool fifo_rdwr = (flags & LNTD_FIFO_RDWR) != 0U;
if (fifo_rdonly && fifo_wronly)
return EINVAL;
if (fifo_rdwr && fifo_rdonly)
return EINVAL;
if (fifo_rdwr && fifo_wronly)
return EINVAL;
unsigned long oflags = 0U;
if (fifo_only)
oflags |= LNTD_KO_FIFO;
if (fifo_rdonly)
oflags |= LNTD_KO_RDONLY;
if (fifo_wronly)
oflags |= LNTD_KO_WRONLY;
if (fifo_rdwr)
oflags |= LNTD_KO_RDWR;
char *pathnamedir;
{
char *xx;
err = lntd_path_dir(&xx, pathname);
if (err != 0)
return err;
pathnamedir = xx;
}
char *pathnamebase;
{
char *xx;
err = lntd_path_base(&xx, pathname);
if (err != 0)
goto free_pathnamedir;
pathnamebase = xx;
}
/* To prevent concurrency issues with the fifo pointed to by
* pathnamedir being deleted or mounted over we need to be
* able to open a file descriptor to it.
*/
lntd_ko realdir;
{
lntd_ko xx;
err = lntd_ko_open(&xx, dirko, pathnamedir,
LNTD_KO_DIRECTORY);
if (err != 0)
goto free_pathnamebase;
realdir = xx;
}
make_fifo:
err = my_mkfifoat(realdir, pathnamebase, mode);
if (err != 0) {
LNTD_ASSUME(err != 0);
/* We can't simply turn this test into an error so we
* can add a LNTD_FIFO_EXCL flag because the fifo
* could be removed by a privileged tmp cleaner style
* program and then created by an enemy.
*/
if (EEXIST == err)
goto open_fifo;
goto close_realdir;
}
open_fifo : {
lntd_ko xx;
err = lntd_ko_open(&xx, realdir, pathnamebase, oflags);
if (ENOENT == err)
goto make_fifo;
if (err != 0)
goto free_pathnamebase;
fd = xx;
}
close_realdir : {
lntd_error close_err = lntd_ko_close(realdir);
LNTD_ASSERT(close_err != EBADF);
if (0 == err)
err = close_err;
}
free_pathnamebase:
lntd_mem_free(pathnamebase);
free_pathnamedir:
lntd_mem_free(pathnamedir);
if (err != 0) {
if (fd != -1) {
lntd_error close_err = lntd_ko_close(fd);
LNTD_ASSERT(close_err != EBADF);
}
return err;
}
*kop = fd;
return 0;
}
#if defined HAVE_MKFIFOAT
static lntd_error my_mkfifoat(int dir, char const *pathname,
mode_t mode)
{
if (-1 == mkfifoat(dir, pathname, mode)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#else
#error no mkfifoat implementation for this platform
#endif
|
mstewartgallus/linted | include/lntd/start.h | <reponame>mstewartgallus/linted<filename>include/lntd/start.h
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_START_H
#define LNTD_START_H
#include <stddef.h>
#if defined HAVE_WINDOWS_API
#include <windows.h>
#endif
/**
* @file
*
* Implements common startup functionality.
*/
struct lntd_start_config {
char const *canonical_process_name;
_Bool dont_init_signals : 1U;
_Bool sanitize_fds : 1U;
_Bool check_privilege : 1U;
};
#ifndef LNTD_START__NO_MAIN
static struct lntd_start_config const lntd_start_config;
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[]);
#endif
#if defined HAVE_WINDOWS_API
int lntd_start_show_command(void);
int lntd_start__main(struct lntd_start_config const *config,
char const **_process_namep, size_t *_argcp,
char const *const **_argvp);
#else
int lntd_start__main(struct lntd_start_config const *config,
unsigned char (*start)(char const *process_name,
size_t argc,
char const *const argv[]),
int argc, char **argv);
#endif
/* This is an awful hack to get linking to work right */
#ifndef LNTD_START__NO_MAIN
#if defined HAVE_WINDOWS_API
/* Hack around a bug in wclang by defining both of these. */
int WINAPI WinMain(HINSTANCE program_instance,
HINSTANCE prev_instance_unused,
char *command_line_unused, int show_command_arg)
{
char const *_process_name;
size_t _argc;
char const *const *_argv;
{
char const *_xx;
size_t _yy;
char const *const *_zz;
int _ww = lntd_start__main(&lntd_start_config, &_xx,
&_yy, &_zz);
if (_ww != 0)
return _ww;
_process_name = _xx;
_argc = _yy;
_argv = _zz;
}
return lntd_start_main(_process_name, _argc, _argv);
}
int WINAPI wWinMain(HINSTANCE program_instance,
HINSTANCE prev_instance_unused,
wchar_t *command_line_unused, int show_command_arg)
{
char const *_process_name;
size_t _argc;
char const *const *_argv;
{
char const *_xx;
size_t _yy;
char const *const *_zz;
int _ww = lntd_start__main(&lntd_start_config, &_xx,
&_yy, &_zz);
if (_ww != 0)
return _ww;
_process_name = _xx;
_argc = _yy;
_argv = _zz;
}
return lntd_start_main(_process_name, _argc, _argv);
}
#else
int main(int argc, char *argv[])
{
return lntd_start__main(&lntd_start_config, lntd_start_main,
argc, argv);
}
#endif
#endif
#endif /* LNTD_START_H */
|
mstewartgallus/linted | src/file/file-windows.c | <gh_stars>0
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/error.h"
#include "lntd/file.h"
#include "lntd/util.h"
lntd_error lntd_file_create(lntd_ko *kop, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode)
{
return LNTD_ERROR_UNIMPLEMENTED;
}
|
mstewartgallus/linted | src/linted-sandbox/sandbox-windows.c | <gh_stars>0
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/dir.h"
#include "lntd/error.h"
#include "lntd/file.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/start.h"
#include "lntd/str.h"
#include "lntd/utf.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <windows.h>
/**
* @file
*
* Sandbox applications.
*/
enum { STOP_OPTIONS,
HELP,
VERSION_OPTION,
WAIT,
TRACEME,
DROP_CAPS,
NO_NEW_PRIVS,
CHDIR,
PRIORITY,
CHROOTDIR,
FSTAB,
WAITER,
NEWUSER_ARG,
NEWPID_ARG,
NEWIPC_ARG,
NEWNET_ARG,
NEWNS_ARG,
NEWUTS_ARG };
static char const *const argstrs[] = {
/**/[STOP_OPTIONS] = "--",
/**/ [HELP] = "--help",
/**/ [VERSION_OPTION] = "--version",
/**/ [WAIT] = "--wait",
/**/ [TRACEME] = "--traceme",
/**/ [DROP_CAPS] = "--dropcaps",
/**/ [NO_NEW_PRIVS] = "--nonewprivs",
/**/ [CHDIR] = "--chdir",
/**/ [PRIORITY] = "--priority",
/**/ [CHROOTDIR] = "--chrootdir",
/**/ [FSTAB] = "--fstab",
/**/ [WAITER] = "--waiter",
/**/ [NEWUSER_ARG] = "--clone-newuser",
/**/ [NEWPID_ARG] = "--clone-newpid",
/**/ [NEWIPC_ARG] = "--clone-newipc",
/**/ [NEWNET_ARG] = "--clone-newnet",
/**/ [NEWNS_ARG] = "--clone-newns",
/**/ [NEWUTS_ARG] = "--clone-newuts"};
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-sandbox",
.dont_init_signals = true,
0};
/**
* @todo Write stderr streams of the child to the system log.
* @todo Pass full command line arguments to process.
*/
static unsigned char lntd_start_main(char const *const process_name,
size_t argc,
char const *const argv[])
{
lntd_error err;
size_t arguments_length = argc;
char const *bad_option = 0;
bool need_version = false;
bool need_help = false;
bool wait = false;
bool traceme = false;
bool no_new_privs = false;
bool drop_caps = false;
bool clone_newuser = false;
bool clone_newpid = false;
bool clone_newipc = false;
bool clone_newnet = false;
bool clone_newns = false;
bool clone_newuts = false;
char const *chdir_path = 0;
char const *priority = 0;
char const *chrootdir = 0;
char const *fstab = 0;
char const *waiter = 0;
bool have_command = false;
size_t command_start;
for (size_t ii = 1U; ii < arguments_length; ++ii) {
char const *argument = argv[ii];
int arg = -1;
for (size_t jj = 0U; jj < LNTD_ARRAY_SIZE(argstrs);
++jj) {
if (0 == strcmp(argument, argstrs[jj])) {
arg = jj;
break;
}
}
switch (arg) {
case -1:
bad_option = argument;
break;
case STOP_OPTIONS:
have_command = true;
command_start = ii;
goto exit_loop;
case HELP:
need_help = true;
break;
case VERSION_OPTION:
need_version = true;
break;
case WAIT:
wait = true;
break;
case TRACEME:
traceme = true;
break;
case NO_NEW_PRIVS:
no_new_privs = true;
break;
case DROP_CAPS:
drop_caps = true;
break;
case CHDIR:
++ii;
if (ii >= arguments_length)
goto exit_loop;
chdir_path = argv[ii];
break;
case PRIORITY:
++ii;
if (ii >= arguments_length)
goto exit_loop;
priority = argv[ii];
break;
case CHROOTDIR:
++ii;
if (ii >= arguments_length)
goto exit_loop;
chrootdir = argv[ii];
break;
case FSTAB:
++ii;
if (ii >= arguments_length)
goto exit_loop;
fstab = argv[ii];
break;
case WAITER:
++ii;
if (ii >= arguments_length)
goto exit_loop;
waiter = argv[ii];
break;
case NEWUSER_ARG:
clone_newuser = true;
break;
case NEWPID_ARG:
clone_newpid = true;
break;
case NEWIPC_ARG:
clone_newipc = true;
break;
case NEWNET_ARG:
clone_newnet = true;
break;
case NEWNS_ARG:
clone_newns = true;
break;
case NEWUTS_ARG:
clone_newuts = true;
break;
}
}
exit_loop:
if (!have_command) {
lntd_log(LNTD_LOG_ERROR, "need command");
return EXIT_FAILURE;
}
if (bad_option != 0) {
lntd_log(LNTD_LOG_ERROR, "bad option: %s", bad_option);
return EXIT_FAILURE;
}
if ((fstab != 0 && 0 == chrootdir) ||
(0 == fstab && chrootdir != 0)) {
lntd_log(
LNTD_LOG_ERROR,
"--chrootdir and --fstab are required together");
return EXIT_FAILURE;
}
struct setting {
char const *name;
bool set;
};
struct setting const settings[] = {
{"--chdir", chdir_path},
{"--traceme", traceme},
{"--nonewprivs", no_new_privs},
{"--dropcaps", drop_caps},
{"--fstab", fstab},
{"--chrootdir", chrootdir != 0},
{"--priority", priority != 0},
{"--waiter", waiter != 0},
{"--clone-newuser", clone_newuser},
{"--clone-newpid", clone_newpid},
{"--clone-newipc", clone_newipc},
{"--clone-newnet", clone_newnet},
{"--clone-newns", clone_newns},
{"--clone-newuts", clone_newuts}};
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(settings); ++ii) {
struct setting const *setting = &settings[ii];
char const *name = setting->name;
bool set = setting->set;
if (set) {
lntd_log(LNTD_LOG_ERROR,
"the option `%s' is not "
"implemented on this "
"platform",
name);
return EXIT_FAILURE;
}
}
char const **command = (char const **)argv + 1U + command_start;
char *command_base;
{
char *xx;
err = lntd_path_base(&xx, command[0U]);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_path_base: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
command_base = xx;
}
char const *binary = command[0U];
command[0U] = command_base;
char *binary_base;
{
char *xx;
err = lntd_path_base(&xx, binary);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_path_base: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
binary_base = xx;
}
wchar_t *binary_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(binary, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_utf_1_to_2: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
binary_utf2 = xx;
}
wchar_t *binary_base_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(binary_base, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_utf_1_to_2: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
binary_base_utf2 = xx;
}
lntd_ko monitor_handle;
lntd_ko thread_handle;
{
DWORD creation_flags = 0U;
STARTUPINFO startup_info = {0};
startup_info.cb = sizeof startup_info;
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdInput = LNTD_KO_STDIN;
startup_info.hStdOutput = LNTD_KO_STDOUT;
startup_info.hStdError = LNTD_KO_STDERR;
PROCESS_INFORMATION process_information;
if (!CreateProcess(binary_utf2, binary_base_utf2, 0, 0,
false, creation_flags, 0, 0,
&startup_info,
&process_information)) {
lntd_log(LNTD_LOG_ERROR, "CreateProcessW: %s",
lntd_error_string(HRESULT_FROM_WIN32(
GetLastError())));
return EXIT_FAILURE;
}
monitor_handle = process_information.hProcess;
thread_handle = process_information.hThread;
}
lntd_ko_close(thread_handle);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "spawning: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
lntd_ko_close(LNTD_KO_STDIN);
lntd_ko_close(LNTD_KO_STDOUT);
if (!wait)
return EXIT_SUCCESS;
switch (WaitForSingleObject(monitor_handle, INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
lntd_log(LNTD_LOG_ERROR, "WaitForSingleObject: %s",
lntd_error_string(
HRESULT_FROM_WIN32(GetLastError())));
return EXIT_FAILURE;
default:
LNTD_ASSERT(false);
}
DWORD xx;
if (!GetExitCodeProcess(monitor_handle, &xx)) {
lntd_log(LNTD_LOG_ERROR, "GetExitCodeProcess: %s",
lntd_error_string(
HRESULT_FROM_WIN32(GetLastError())));
return EXIT_FAILURE;
}
return xx;
}
|
mstewartgallus/linted | include/lntd/admin.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ADMIN_H
#define LNTD_ADMIN_H
#include "lntd/error.h"
#include "lntd/ko.h"
#include <stddef.h>
#include <stdint.h>
/**
* @file
*
* Monitor, probe and control an init process.
*/
struct lntd_async_pool;
struct lntd_async_task;
union lntd_async_ck;
typedef int_least32_t lntd_admin_bool;
typedef int_least32_t lntd_admin_enum;
typedef lntd_ko lntd_admin_in;
typedef lntd_ko lntd_admin_out;
enum { LNTD_ADMIN_ADD_UNIT,
LNTD_ADMIN_ADD_SOCKET,
LNTD_ADMIN_STATUS,
LNTD_ADMIN_STOP };
typedef lntd_admin_enum lntd_admin_type;
struct lntd_admin_request_add_unit {
char *name;
char *fstab;
char *chdir_path;
struct {
uint_least32_t command_len;
char **command_val;
} command;
struct {
uint_least32_t environment_len;
char **environment_val;
} environment;
int_least64_t *timer_slack_nsec;
int_least64_t *priority;
int_least64_t *limit_no_file;
int_least64_t *limit_msgqueue;
int_least64_t *limit_locks;
int_least64_t *limit_memlock;
lntd_admin_bool clone_newuser;
lntd_admin_bool clone_newcgroup;
lntd_admin_bool clone_newpid;
lntd_admin_bool clone_newipc;
lntd_admin_bool clone_newnet;
lntd_admin_bool clone_newns;
lntd_admin_bool clone_newuts;
lntd_admin_bool no_new_privs;
lntd_admin_bool seccomp;
};
struct lntd_admin_request_add_socket {
char *name;
char *path;
int_least32_t fifo_size;
int_least32_t sock_type;
};
struct lntd_admin_request_status {
char *name;
};
struct lntd_admin_request_stop {
char *name;
};
struct lntd_admin_request {
lntd_admin_type type;
union {
struct lntd_admin_request_add_unit add_unit;
struct lntd_admin_request_add_socket add_socket;
struct lntd_admin_request_status status;
struct lntd_admin_request_stop stop;
} lntd_admin_request_u;
};
struct lntd_admin_reply_add_unit {
char dummy;
};
struct lntd_admin_reply_add_socket {
char dummy;
};
struct lntd_admin_reply_status {
lntd_admin_bool is_up;
};
struct lntd_admin_reply_stop {
lntd_admin_bool was_up;
};
struct lntd_admin_reply {
lntd_admin_type type;
union {
struct lntd_admin_reply_add_unit add_unit;
struct lntd_admin_reply_add_socket add_socket;
struct lntd_admin_reply_status status;
struct lntd_admin_reply_stop stop;
} lntd_admin_reply_u;
};
struct lntd_admin_in_task_recv;
struct lntd_admin_out_task_send;
lntd_error
lntd_admin_in_task_recv_create(struct lntd_admin_in_task_recv **taskp,
void *data);
void lntd_admin_in_task_recv_destroy(
struct lntd_admin_in_task_recv *task);
lntd_error
lntd_admin_in_task_recv_request(struct lntd_admin_request **outp,
struct lntd_admin_in_task_recv *task);
void lntd_admin_request_free(struct lntd_admin_request *outp);
void *
lntd_admin_in_task_recv_data(struct lntd_admin_in_task_recv *task);
void lntd_admin_in_task_recv_submit(
struct lntd_async_pool *pool, struct lntd_admin_in_task_recv *task,
union lntd_async_ck task_ck, void *userstate, lntd_ko ko);
void lntd_admin_in_task_recv_cancel(
struct lntd_admin_in_task_recv *task);
lntd_error
lntd_admin_out_task_send_create(struct lntd_admin_out_task_send **taskp,
void *data);
void lntd_admin_out_task_send_destroy(
struct lntd_admin_out_task_send *task);
void lntd_admin_out_task_send_submit(
struct lntd_async_pool *pool, struct lntd_admin_out_task_send *task,
union lntd_async_ck task_ck, void *userstate, lntd_ko ko,
struct lntd_admin_reply const *reply);
void *
lntd_admin_out_task_send_data(struct lntd_admin_out_task_send *task);
void lntd_admin_out_task_send_cancel(
struct lntd_admin_out_task_send *task);
lntd_error lntd_admin_in_send(lntd_admin_in admin,
struct lntd_admin_request const *request);
lntd_error lntd_admin_out_recv(lntd_admin_out admin,
struct lntd_admin_reply *reply);
#endif /* LNTD_ADMIN_H */
|
mstewartgallus/linted | src/linted-waiter/waiter.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/prctl.h"
#include "lntd/start.h"
#include "lntd/util.h"
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static void on_term(int signo);
static void on_sigchld(int signo, siginfo_t *infop, void *foo);
static void do_nothing(int signo);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-waiter",
.dont_init_signals = true};
static int const various_sigs[] = {SIGCONT};
static int const exit_signals[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
char *service;
{
char *xx;
err = lntd_env_get("LINTED_SERVICE", &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
service = xx;
}
if (service != 0) {
err = lntd_prctl_set_name(service);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_prctl_set_name: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
lntd_mem_free(service);
}
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(various_sigs); ++ii) {
struct sigaction action = {0};
action.sa_handler = do_nothing;
sigemptyset(&action.sa_mask);
if (-1 == sigaction(various_sigs[ii], &action, NULL)) {
lntd_log(LNTD_LOG_ERROR, "sigaction: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(exit_signals); ++ii) {
struct sigaction action = {0};
action.sa_handler = on_term;
sigemptyset(&action.sa_mask);
if (-1 == sigaction(exit_signals[ii], &action, NULL)) {
lntd_log(LNTD_LOG_ERROR, "sigaction: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
{
struct sigaction action = {0};
action.sa_sigaction = on_sigchld;
action.sa_flags = SA_SIGINFO;
sigemptyset(&action.sa_mask);
if (-1 == sigaction(SIGCHLD, &action, NULL)) {
lntd_log(LNTD_LOG_ERROR, "sigaction: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
{
char *buf = 0;
size_t n = 0U;
for (;;) {
ssize_t zz;
{
char *xx = buf;
size_t yy = n;
errno = 0;
zz = getline(&xx, &yy, stdin);
buf = xx;
n = yy;
}
if (-1 == zz) {
err = errno;
if (0 == err)
break;
if (EINTR == err)
continue;
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"getline: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
lntd_log(LNTD_LOG_ERROR, "%s", buf);
}
lntd_mem_free(buf);
}
/* Make sure to only exit after having fully drained the pipe
* of errors to be logged. */
{
struct sigaction action = {0};
action.sa_handler = do_nothing;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
if (-1 == sigaction(SIGCHLD, &action, NULL)) {
lntd_log(LNTD_LOG_ERROR, "sigaction: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
for (;;) {
int wait_status;
{
int xx;
wait_status = waitpid(-1, &xx, __WALL);
}
if (-1 == wait_status) {
err = errno;
LNTD_ASSUME(err != 0);
if (ECHILD == err)
break;
if (EINTR == err)
continue;
LNTD_ASSERT(false);
}
}
return EXIT_SUCCESS;
}
static void on_term(int signo)
{
lntd_error old_err = errno;
if (-1 == kill(-getpgrp(), signo)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
/* This is fine */
if (ESRCH == err)
goto prevent_looping;
LNTD_ASSERT(err != LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(err != LNTD_ERROR_PERMISSION);
LNTD_ASSERT(false);
}
prevent_looping:
;
sigset_t exitset;
sigemptyset(&exitset);
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(exit_signals); ++ii)
sigaddset(&exitset, exit_signals[ii]);
struct timespec timeout = {0};
for (;;) {
siginfo_t info;
if (-1 == sigtimedwait(&exitset, &info, &timeout)) {
lntd_error err = errno;
if (EINTR == err)
continue;
LNTD_ASSERT(EAGAIN == err);
break;
}
}
errno = old_err;
}
static void on_sigchld(int signo, siginfo_t *infop, void *foo)
{
lntd_error old_err = errno;
for (;;) {
int wait_status;
{
int xx;
wait_status =
waitpid(-1, &xx, __WALL | WNOHANG);
}
if (-1 == wait_status) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
if (ECHILD == err)
break;
if (EINTR == err)
continue;
LNTD_ASSERT(false);
}
if (0U == wait_status)
break;
}
errno = old_err;
}
static void do_nothing(int signo)
{
}
|
mstewartgallus/linted | src/str/str.c | <reponame>mstewartgallus/linted
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/str.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static lntd_error valloc_sprintf(char **strbp, size_t *sizep,
const char *fmt, va_list ap)
LNTD_FORMAT(__printf__, 3, 0);
lntd_error lntd_str_dup(char **resultp, char const *input)
{
return lntd_str_dup_len(resultp, input, SIZE_MAX);
}
#if defined HAVE_WINDOWS_API
lntd_error lntd_str_dup_len(char **resultp, char const *input, size_t n)
{
size_t ii = 0U;
for (; ii < n; ++ii)
if ('\0' == input[ii])
break;
size_t len = ii;
lntd_error err = 0;
char *copy;
{
void *xx;
err = lntd_mem_alloc(&xx, len + 1U);
if (err != 0)
return err;
copy = xx;
}
memcpy(copy, input, len);
copy[len] = '\0';
*resultp = copy;
return 0;
}
#else
lntd_error lntd_str_dup_len(char **resultp, char const *input, size_t n)
{
char *result = strndup(input, n);
if (0 == result) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
*resultp = result;
return 0;
}
#endif
lntd_error lntd_str_append(char **bufp, size_t *capp, size_t *sizep,
char const *str, size_t strsize)
{
lntd_error err;
char *buf = *bufp;
size_t cap = *capp;
size_t size = *sizep;
if (size > SIZE_MAX - strsize)
return LNTD_ERROR_OUT_OF_MEMORY;
size_t new_size = size + strsize;
size_t new_cap = cap;
if (new_size > cap) {
new_cap = new_size;
char *new_buf;
{
void *xx;
err = lntd_mem_realloc(&xx, buf, new_cap);
if (err != 0)
return err;
new_buf = xx;
}
buf = new_buf;
}
if (strsize > 0U)
memcpy(buf + size, str, strsize);
cap = new_cap;
size = new_size;
*bufp = buf;
*capp = cap;
*sizep = size;
return 0;
}
lntd_error lntd_str_append_cstring(char **bufp, size_t *capp,
size_t *sizep, char const *str)
{
return lntd_str_append(bufp, capp, sizep, str, strlen(str));
}
lntd_error lntd_str_format(char **strp, char const *format, ...)
{
va_list ap;
va_start(ap, format);
lntd_error err = valloc_sprintf(strp, 0, format, ap);
va_end(ap);
return err;
}
lntd_error lntd_str_append_format(char **bufp, size_t *capp,
size_t *sizep, char const *fmt, ...)
{
lntd_error err = 0;
size_t strsize;
char *str;
{
va_list ap;
va_start(ap, fmt);
{
char *xx;
size_t yy;
err = valloc_sprintf(&xx, &yy, fmt, ap);
if (err != 0)
goto free_ap;
str = xx;
strsize = yy;
}
free_ap:
va_end(ap);
if (err != 0)
return err;
}
err = lntd_str_append(bufp, capp, sizep, str, strsize);
lntd_mem_free(str);
return err;
}
static lntd_error valloc_sprintf(char **strp, size_t *sizep,
const char *fmt, va_list ap)
{
lntd_error err = 0;
va_list ap_copy;
va_copy(ap_copy, ap);
int bytes_should_write;
#if defined HAVE_WINDOWS_API
bytes_should_write = vsprintf_s(0, 0, fmt, ap);
#else
bytes_should_write = vsnprintf(0, 0, fmt, ap);
#endif
if (bytes_should_write < 0) {
err = errno;
LNTD_ASSUME(err != 0);
goto free_ap_copy;
}
{
size_t string_size = 1U + (unsigned)bytes_should_write;
char *string;
{
void *xx;
err = lntd_mem_alloc(&xx, string_size);
if (err != 0)
goto free_ap_copy;
string = xx;
}
int res;
#if defined HAVE_WINDOWS_API
res = vsprintf_s(string, string_size, fmt, ap_copy);
#else
res = vsnprintf(string, string_size, fmt, ap_copy);
#endif
if (res < 0) {
lntd_mem_free(string);
err = errno;
LNTD_ASSUME(err != 0);
goto free_ap_copy;
}
if (sizep != 0)
*sizep = (unsigned)bytes_should_write;
*strp = string;
}
free_ap_copy:
va_end(ap_copy);
return err;
}
|
mstewartgallus/linted | src/linted-init/init-windows.c | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/path.h"
#include "lntd/start.h"
#include "lntd/str.h"
#include "lntd/utf.h"
#include "lntd/util.h"
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
/**
* @file
*
* @todo Windows: delegate exit signals from `init` to `monitor`.
*/
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-init", 0};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err;
char const *monitor;
{
char *xx;
err = lntd_env_get("LINTED_MONITOR", &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
monitor = xx;
}
if (0 == monitor) {
lntd_log(LNTD_LOG_ERROR,
"%s is a required environment variable",
"LINTED_MONITOR");
return EXIT_FAILURE;
}
char *monitor_base;
{
char *xx;
err = lntd_path_base(&xx, monitor);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_path_base: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
monitor_base = xx;
}
wchar_t *monitor_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(monitor, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_utf_1_to_2: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
monitor_utf2 = xx;
}
wchar_t *monitor_base_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(monitor_base, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_utf_1_to_2: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
monitor_base_utf2 = xx;
}
for (;;) {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: spawning %s\n", process_name,
monitor_base);
lntd_ko monitor_handle;
lntd_ko thread_handle;
{
DWORD creation_flags = 0U;
STARTUPINFO startup_info = {0};
startup_info.cb = sizeof startup_info;
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdInput = LNTD_KO_STDIN;
startup_info.hStdOutput = LNTD_KO_STDOUT;
startup_info.hStdError = LNTD_KO_STDERR;
PROCESS_INFORMATION process_information;
if (!CreateProcessW(
monitor_utf2, monitor_base_utf2, 0, 0,
false, creation_flags, 0, 0,
&startup_info, &process_information)) {
lntd_log(LNTD_LOG_ERROR,
"CreateProcessW: %s",
lntd_error_string(
HRESULT_FROM_WIN32(
GetLastError())));
return EXIT_FAILURE;
}
monitor_handle = process_information.hProcess;
thread_handle = process_information.hThread;
}
lntd_ko_close(thread_handle);
switch (WaitForSingleObject(monitor_handle, INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
lntd_log(LNTD_LOG_ERROR,
"WaitForSingleObject: %s",
lntd_error_string(HRESULT_FROM_WIN32(
GetLastError())));
return EXIT_FAILURE;
default:
LNTD_ASSERT(false);
}
DWORD exit_status;
{
DWORD xx;
if (!GetExitCodeProcess(monitor_handle, &xx)) {
lntd_log(LNTD_LOG_ERROR,
"GetExitCodeProcess: %s",
lntd_error_string(
HRESULT_FROM_WIN32(
GetLastError())));
return EXIT_FAILURE;
}
exit_status = xx;
}
if (EXIT_SUCCESS == exit_status)
goto exit_loop;
lntd_io_write_format(LNTD_KO_STDERR, 0,
"monitor exited with %lu\n",
exit_status);
lntd_ko_close(monitor_handle);
}
exit_loop:
return EXIT_SUCCESS;
}
|
mstewartgallus/linted | docs/process-management.h | <filename>docs/process-management.h
/* Copyright (C) 2014, 2015 <NAME>
*
* Copying and distribution of this file, with or without modification,
* are permitted in any medium without royalty provided the copyright
* notice and this notice are preserved.
*/
/**
@file
Linted -- Process Management
@section lifecycle Life-Cycle
- `linted` -> `init`
- `monitor`
- `startup`
- services
First, the `linted` process starts up. It sets a few environment
variables or possibly displays some sort of help.
Next, the `linted` binary executes and becomes the `init` process.
Using some of the set environment variables it forks off and spawns the
`monitor` process.
The `monitor` process then sets up a little bit of state such as
important IPC channels and then spawns the `startup` process. After
spawning the `startup` process the `monitor` process then idly waits for
commands.
Meanwhile, the `startup` process reads through the unit files in the
directories listed in `LINTED_UNIT_PATH` and registers those units
with the `monitor`. Once the `monitor` receives units to register it
then spawns associated processes or creates associated files. In the
future, I would like to have the `monitor` automatically deduce unit
file dependencies and only spawn processes once their dependencies are
met.
@section hierarchy Process hierarchy
- `init`
- `monitor`
- `audio`
- `audio`
- `simulator`
- `simulator`
- `drawer`
- `drawer`
- `gui`
- `gui`
- `window`
- `window`
`init` is the top level service that contains everything using
`PR_SET_CHILD_SUBREAPER`. All it does is monitor and restart the
`monitor` process and delegate signals to it.
Underneath `init` the `monitor` process monitors and restarts service
processes and delegates signals.
Service processes underneath `init` using `PR_SET_CHILD_SUBREAPER` or
`CLONE_NEWPID` contain underneath them similarly named processes that do
the actual work of the service. Service processes don't actually
monitor or restart their children. That job is delegated to `monitor`
who ptraces and monitor these service processes (but not the children of
the service processes.) `monitor` manually kills any children of dying
`PR_SET_CHILD_SUBREAPER` type sandboxes and children of dying
`CLONE_NEWPID` type sandboxes are killed by the kernel automatically.
When `init` dies `monitor` will receive a `SIGHUP` because `init` will
be the controlling process for the controlling terminal (if there is a
terminal) or from a `SIGKILL` from a set parent death signal.
@bug Currently not all sandboxed processes are killed on `init`
death. Possible solutions:
- `monitor` could ptrace `init` and kill its children when `init`
is about to die.
- Sandboxes could use `PR_SET_PDEATHSIG` once they have been
reparented to `init`. However, I am not sure how they would wait
until they have been reparented to `init` before using
`PR_SET_PDEATHSIG`.
@section errors Error Handling
There are two main types of faults: transient faults and persistent
faults.
There are transient faults such as memory corruption which can be
resolved by aborting and letting the process monitor restart the
process.
There are permanent faults such as logic errors or unsupported system
configurations for which the process monitor should not restart the
process and for which the system should notify the user and wait for
user input.
Transient faults are probably best mapped to UNIX signals and
permanent faults to nonzero process exit codes.
@section ipc IPC
So far we have chosen to use file FIFOs as they can be easily bound in
and outside of sandboxes.
@subsection requirements Requirements
- Presents a security boundary.
- Allows access control between sandboxes.
- Does not allow a reader to interfere with the writer.
- Does not allow a writer to interfere with the reader.
@subsection previous Previous Work
- The Xen hypervisor's shared memory I/O.
@subsection rejected Rejected Approaches
- UNIX domain sockets are really messy.
@subsection ipcsolutions Full Solutions
These are full blown solutions that handle both encoding data and
transporting data.
- D-Bus
- gRPC
- SOAP
- CORBA
- Apache Avro
- Apache Thrift
- XDR
@subsection ipcencodings Encodings
Currently we just use very arbitrary hacks for encoding our data.
- Plain Text
- XML
- S-Expressions
- JSON
- CSV
- OGDL
- OpenDDL
- Binary
- Schemaless
- SDXF
- Fast Infoset (basically binary XML)
- BSON, UBJSON, Smile
- MessagePack
- Binn
- Schema
- Google Protocol Buffers
- Capn Proto
- ASN.1 Compiler
@subsection ipcprimitives Primitives
@subsubsection files Files
File types:
- Eventfds
- Sockets
- UNIX Domain Sockets
- Netlink Sockets
- Network Sockets
- Regular files
- Directory files
- Symlink
- FIFOs
- Unix domain sockets
- POSIX Message Queues
- Character devices
- Pseudo-terminal handles
- Block devices
- Custom FUSE files
Filesystem visible files:
- Regular files
- Directory files
- Symlink
- FIFOs
- Unix domain sockets
- POSIX Message Queues
- Character devices
- Pseudo-terminal handles
- Block devices
- Custom FUSE files
@subsubsection fifos FIFOs
FIFOs give `POLLHUP` to poll and read zero bytes once a process has
written to the pipe once and there are no more open writers. As well,
fifos give `EPIPE` to writers when a process writes to the pipe and
there are no more open readers. Moreover, fifos cannot be opened with
write only permission nonblockingly (they give `ENXIO` errors) when
there are not open readers. For these reasons most of our fifo users
should open these fifos in read and write mode and not write only or
read only mode.
@subsubsection signals Signals
- Regular signals
- Realtime signals
@subsubsection sharedmemory Shared Memory
System calls that allocate memory:
- `mmap`
- `brk`
- Use the `DRM_IOCTL_I915_GEM_MMAP` `ioctl`
- Use the `DRM_IOCTL_RADEON_GEM_MMAP` `ioctl`
- `shmat`
- `prctl` (using `PR_SET_MM_BRK`)
Shared memory is unsuitable because:
- `mmap`able files can be `ftruncate`d by attackers
- We can only share memory mappings without files using a weird trick
using `fork`.
- File sealing only works on `shmfs` (files created using
`memfd_create`) and those files cannot be mounted.
- System V IPC sort of works but is awkward. Sandboxed processes
would have to share the same IPC namespace (and so would have
access every shared memory segment), `shmget` does sets the initial
size of the memory segment which cannot be changed later and so
attackers can't create `SIGSEGV`s in users.
- Hilariously, it is possible to use `mmap` with netlink sockets
(which should only be used for kernel space to user-space
communication) and so achieve safe `mmap` between processes.
@subsubsection sysvipc System V IPC
System V IPC types:
- message queues
- semaphore sets
- shared memory segments
@section sandboxing Sandboxing
I cannot use AppArmor as it requires root privileges in order to
load a profile into the kernel in the first place.
Currently the following are used:
- Seccomp
- Process namespaces
We could use:
- `setxattr` or `setfacl` to set values under the "security" and
"security.posix_acl_access" namespace. It's only attributes other
than security ones that don't work. However, this seems like it
requires multi-UID user accounts to work.
Approaches that won't work:
- We cannot use `FS_IOC_SETFLAGS` to set flags such as the append only
and immutable flags because `tmpfs` does not support such flags. Also
even in sandbox land we'll probably lack the appropriate permissions.
See also:
- http://www.chromium.org/developers/design-documents/sandbox
- http://www.cl.cam.ac.uk/research/security/capsicum/
@section signals Signal handling
Currently `init` forwards all nonurgent exit signals (`SIGHUP`,
`SIGINT1`, `SIGQUIT`, and `SIGTERM`) to the `monitor` to handle them.
*/
|
mstewartgallus/linted | src/spawn/spawn.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/spawn.h"
#include "lntd/error.h"
#include "lntd/execveat.h"
#include "lntd/fifo.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/prctl.h"
#include "lntd/proc.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <syscall.h>
#include <unistd.h>
extern char **environ;
enum { LNTD_SIGNAL_HUP,
LNTD_SIGNAL_CHLD,
LNTD_SIGNAL_INT,
LNTD_SIGNAL_TERM,
LNTD_SIGNAL_QUIT,
NUM_SIGS };
static int const signals[NUM_SIGS] = {[LNTD_SIGNAL_HUP] = SIGHUP,
[LNTD_SIGNAL_CHLD] = SIGCHLD,
[LNTD_SIGNAL_INT] = SIGINT,
[LNTD_SIGNAL_QUIT] = SIGQUIT,
[LNTD_SIGNAL_TERM] = SIGTERM};
struct lntd_spawn_file_actions {
lntd_ko new_stdin;
lntd_ko new_stdout;
lntd_ko new_stderr;
bool set_stdin : 1U;
bool set_stdout : 1U;
bool set_stderr : 1U;
};
struct lntd_spawn_attr {
bool die_on_parent_death : 1U;
};
struct fork_args {
sigset_t const *sigset;
struct lntd_spawn_file_actions const *file_actions;
char const *const *argv;
char const *const *envp;
char const *binary;
lntd_ko dirko;
lntd_ko err_writer;
bool die_on_parent_death : 1U;
};
static int fork_routine(void *args);
static pid_t safe_vfork(int (*f)(void *), void *args);
static lntd_error duplicate_to(lntd_ko new, lntd_ko old);
lntd_error lntd_spawn_attr_init(struct lntd_spawn_attr **attrp)
{
lntd_error err;
struct lntd_spawn_attr *attr;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *attr);
if (err != 0)
return err;
attr = xx;
}
attr->die_on_parent_death = false;
*attrp = attr;
return 0;
}
void lntd_spawn_attr_destroy(struct lntd_spawn_attr *attr)
{
lntd_mem_free(attr);
}
void lntd_spawn_attr_set_die_on_parent_death(
struct lntd_spawn_attr *attrp)
{
attrp->die_on_parent_death = true;
}
lntd_error lntd_spawn_file_actions_init(
struct lntd_spawn_file_actions **file_actionsp)
{
lntd_error err;
struct lntd_spawn_file_actions *file_actions;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *file_actions);
if (err != 0)
return err;
file_actions = xx;
}
file_actions->set_stdin = false;
file_actions->set_stdout = false;
file_actions->set_stderr = false;
*file_actionsp = file_actions;
return 0;
}
void lntd_spawn_file_actions_set_stdin(
struct lntd_spawn_file_actions *file_actions, lntd_ko newko)
{
file_actions->new_stdin = newko;
file_actions->set_stdin = true;
}
void lntd_spawn_file_actions_set_stdout(
struct lntd_spawn_file_actions *file_actions, lntd_ko newko)
{
file_actions->new_stdout = newko;
file_actions->set_stdout = true;
}
void lntd_spawn_file_actions_set_stderr(
struct lntd_spawn_file_actions *file_actions, lntd_ko newko)
{
file_actions->new_stderr = newko;
file_actions->set_stderr = true;
}
void lntd_spawn_file_actions_destroy(
struct lntd_spawn_file_actions *file_actions)
{
lntd_mem_free(file_actions);
}
lntd_error
lntd_spawn(lntd_proc *childp, lntd_ko dirko, char const *binary,
struct lntd_spawn_file_actions const *file_actions,
struct lntd_spawn_attr const *attr, char const *const argv[],
char const *const envp[])
{
lntd_error err = 0;
if (LNTD_KO_CWD != dirko && dirko > INT_MAX)
return EBADF;
if ('/' == binary[0U])
dirko = LNTD_KO_CWD;
sigset_t const *child_mask = 0;
bool die_on_parent_death = false;
if (attr != 0) {
die_on_parent_death = attr->die_on_parent_death;
}
lntd_ko err_reader;
lntd_ko err_writer;
{
lntd_ko xx;
lntd_ko yy;
err = lntd_fifo_pair(&xx, &yy, 0);
if (err != 0)
return err;
err_reader = xx;
err_writer = yy;
}
/* Greater than standard input, standard output and standard
* error */
unsigned greatest = 4U;
/* Copy file descriptors in case they get overridden */
if (file_actions != 0 && err_writer < greatest) {
int err_writer_copy =
fcntl(err_writer, F_DUPFD_CLOEXEC, (long)greatest);
if (-1 == err_writer_copy) {
err = errno;
LNTD_ASSUME(err != 0);
goto close_err_pipes;
}
lntd_ko_close(err_writer);
err_writer = err_writer_copy;
}
lntd_ko dirko_copy;
bool dirko_copied = false;
if (LNTD_KO_CWD == dirko) {
dirko_copy = LNTD_KO_CWD;
} else if (file_actions != 0 && dirko < greatest) {
int fd = fcntl(dirko, F_DUPFD_CLOEXEC, (long)greatest);
if (-1 == fd) {
err = errno;
LNTD_ASSUME(err != 0);
goto close_err_pipes;
}
dirko_copy = fd;
dirko_copied = true;
} else {
dirko_copy = dirko;
}
pid_t child = -1;
{
sigset_t sigset;
sigfillset(&sigset);
if (0 == child_mask)
child_mask = &sigset;
err = pthread_sigmask(SIG_BLOCK, &sigset, &sigset);
if (err != 0)
goto close_dirko_copy;
struct fork_args fork_args = {
.sigset = child_mask,
.file_actions = file_actions,
.err_writer = err_writer,
.die_on_parent_death = die_on_parent_death,
.argv = argv,
.envp = envp,
.dirko = dirko_copy,
.binary = binary};
child = safe_vfork(fork_routine, &fork_args);
LNTD_ASSERT(child != 0);
lntd_error mask_err =
pthread_sigmask(SIG_SETMASK, &sigset, 0);
if (0 == err)
err = mask_err;
}
close_dirko_copy:
if (dirko_copied)
lntd_ko_close(dirko_copy);
close_err_pipes : {
lntd_error close_err = lntd_ko_close(err_writer);
if (0 == err)
err = close_err;
}
if (err != 0)
goto close_err_reader;
{
size_t xx;
lntd_error yy;
err = lntd_io_read_all(err_reader, &xx, &yy, sizeof yy);
if (err != 0)
goto close_err_reader;
/* If bytes_read is zero then a succesful exec
* occured */
if (xx == sizeof yy) {
err = yy;
LNTD_ASSUME(err != 0);
}
}
close_err_reader : {
lntd_error close_err = lntd_ko_close(err_reader);
if (0 == err)
err = close_err;
}
if (err != 0)
return err;
if (childp != 0)
*childp = child;
return 0;
}
LNTD_NO_SANITIZE_ADDRESS static int fork_routine(void *arg)
{
struct fork_args *args = arg;
sigset_t const *sigset = args->sigset;
struct lntd_spawn_file_actions const *file_actions =
args->file_actions;
lntd_ko err_writer = args->err_writer;
char const *const *argv = args->argv;
char const *const *envp = args->envp;
lntd_ko dirko = args->dirko;
char const *binary = args->binary;
bool die_on_parent_death = args->die_on_parent_death;
lntd_error err = 0;
/*
* Get rid of signal handlers so that they can't be called
* before execve.
*/
/* We need to use the direct system call to trample over OS
* signals. */
for (int ii = 1; ii < NSIG; ++ii) {
/* Uncatchable, avoid Valgrind warnings */
if (SIGSTOP == ii || SIGKILL == ii)
continue;
struct sigaction action;
if (-1 ==
syscall(__NR_rt_sigaction, ii, 0, &action, 8U)) {
err = errno;
goto fail;
}
if (SIG_IGN == action.sa_handler)
continue;
action.sa_handler = SIG_DFL;
if (-1 ==
syscall(__NR_rt_sigaction, ii, &action, 0, 8U)) {
err = errno;
goto fail;
}
}
err = pthread_sigmask(SIG_SETMASK, sigset, 0);
if (err != 0)
goto fail;
{
sigset_t set;
sigemptyset(&set);
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(signals);
++ii) {
sigaddset(&set, signals[ii]);
}
err = pthread_sigmask(SIG_UNBLOCK, &set, 0);
if (err != 0)
goto fail;
}
lntd_ko new_stdin;
lntd_ko new_stdout;
lntd_ko new_stderr;
bool set_stdin = false;
bool set_stdout = false;
bool set_stderr = false;
if (file_actions != 0) {
set_stdin = file_actions->set_stdin;
set_stdout = file_actions->set_stderr;
set_stderr = file_actions->set_stdout;
if (set_stdin)
new_stdin = file_actions->new_stdin;
if (set_stdout)
new_stdout = file_actions->new_stdout;
if (set_stderr)
new_stderr = file_actions->new_stderr;
}
if (die_on_parent_death) {
err = lntd_prctl_set_death_sig(SIGKILL);
if (err != 0)
goto fail;
}
if (set_stdin) {
err = duplicate_to(new_stdin, STDIN_FILENO);
if (err != 0)
goto fail;
}
if (set_stdout) {
err = duplicate_to(new_stdout, STDOUT_FILENO);
if (err != 0)
goto fail;
}
if (set_stderr) {
err = duplicate_to(new_stderr, STDERR_FILENO);
if (err != 0)
goto fail;
}
if (0 == envp)
envp = (char const *const *)environ;
if (LNTD_KO_CWD == dirko || '/' == binary[0U]) {
execve(binary, (char *const *)argv,
(char *const *)envp);
err = errno;
} else {
err = lntd_execveat(dirko, binary, (char **)argv,
(char **)envp, 0);
}
fail : {
lntd_error xx = err;
lntd_io_write_all(err_writer, 0, &xx, sizeof xx);
}
return EXIT_FAILURE;
}
LNTD_NO_SANITIZE_ADDRESS
static lntd_error duplicate_to(lntd_ko new, lntd_ko old)
{
lntd_error err = 0;
if (new == old) {
int flags = fcntl(old, F_GETFD);
if (-1 == flags) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
if (-1 == fcntl(new, F_SETFD, flags & ~FD_CLOEXEC)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
/*
* The state of a file descriptor after close gives an EINTR
* error is unspecified by POSIX so this function avoids the
* problem by simply blocking all signals.
*/
sigset_t sigset;
/* First use the signal set for the full set */
sigfillset(&sigset);
/* Then reuse the signal set for the old set */
err = pthread_sigmask(SIG_BLOCK, &sigset, &sigset);
if (err != 0)
return err;
if (-1 == dup2(new, old)) {
err = errno;
LNTD_ASSUME(err != 0);
} else {
err = 0;
}
lntd_error mask_err = pthread_sigmask(SIG_SETMASK, &sigset, 0);
if (0 == err)
err = mask_err;
return err;
}
/* Most compilers can't handle the weirdness of vfork so contain it in
* a safe abstraction.
*/
LNTD_NOINLINE LNTD_NOCLONE LNTD_NO_SANITIZE_ADDRESS static pid_t
safe_vfork(int (*volatile f)(void *), void *volatile arg)
{
pid_t child = vfork();
if (0 == child)
_Exit(f(arg));
return child;
}
|
mstewartgallus/linted | src/window/window-windows.c | <reponame>mstewartgallus/linted<filename>src/window/window-windows.c<gh_stars>0
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/window.h"
#include "lntd/async.h"
#include "lntd/io.h"
#include "lntd/mem.h"
#include "lntd/rpc.h"
#include "lntd/util.h"
#include <errno.h>
#include <stdint.h>
#include <windows.h>
lntd_error lntd_window_write(lntd_window window, uint_fast32_t in)
{
char buf[LNTD_RPC_UINT32_SIZE];
lntd_rpc_pack_uint32(in, buf);
OVERLAPPED overlapped = {0};
overlapped.Offset = 0;
overlapped.OffsetHigh = 0;
if (!WriteFile(window, buf, sizeof buf, 0, &overlapped)) {
lntd_error err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
lntd_error lntd_window_read(lntd_window window, uint_fast32_t *outp)
{
char buf[LNTD_RPC_UINT32_SIZE];
size_t bytes_read;
{
DWORD xx;
OVERLAPPED overlapped = {0};
overlapped.Offset = 0;
overlapped.OffsetHigh = 0;
if (!ReadFile(window, buf, sizeof buf, &xx,
&overlapped)) {
lntd_error err =
HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
bytes_read = xx;
}
if (bytes_read != sizeof buf)
return EPROTO;
*outp = lntd_rpc_unpack_uint32(buf);
return 0;
}
struct lntd_window_task_notify {
struct lntd_io_task_write *parent;
void *data;
};
struct lntd_window_task_watch {
struct lntd_io_task_read *parent;
void *data;
char dummy[1U];
};
lntd_error
lntd_window_task_watch_create(struct lntd_window_task_watch **taskp,
void *data)
{
lntd_error err;
struct lntd_window_task_watch *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_io_task_read *parent;
{
struct lntd_io_task_read *xx;
err = lntd_io_task_read_create(&xx, task);
if (err != 0)
goto free_task;
parent = xx;
}
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_task:
lntd_mem_free(task);
return err;
}
void lntd_window_task_watch_destroy(struct lntd_window_task_watch *task)
{
lntd_io_task_read_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_window_task_watch_submit(struct lntd_async_pool *pool,
struct lntd_window_task_watch *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko notifier)
{
lntd_io_task_read_submit(pool, task->parent, task_ck, userstate,
notifier, task->dummy,
sizeof task->dummy);
}
void *lntd_window_task_watch_data(struct lntd_window_task_watch *task)
{
return task->data;
}
lntd_error
lntd_window_task_notify_create(struct lntd_window_task_notify **taskp,
void *data)
{
lntd_error err;
struct lntd_window_task_notify *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_io_task_write *parent;
{
struct lntd_io_task_write *xx;
err = lntd_io_task_write_create(&xx, task);
if (err != 0)
goto free_task;
parent = xx;
}
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_task:
lntd_mem_free(task);
return err;
}
void lntd_window_task_notify_destroy(
struct lntd_window_task_notify *task)
{
lntd_io_task_write_destroy(task->parent);
lntd_mem_free(task);
}
static const char dummy[1U];
void lntd_window_task_notify_submit(
struct lntd_async_pool *pool, struct lntd_window_task_notify *task,
union lntd_async_ck task_ck, void *userstate, lntd_ko notifier)
{
lntd_io_task_write_submit(pool, task->parent, task_ck,
userstate, notifier, dummy,
sizeof dummy);
}
void *lntd_window_task_notify_data(struct lntd_window_task_notify *task)
{
return task->data;
}
|
mstewartgallus/linted | src/fifo/fifo-windows.c | <reponame>mstewartgallus/linted<filename>src/fifo/fifo-windows.c
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/fifo.h"
#include "lntd/error.h"
#include <windows.h>
lntd_error lntd_fifo_pair(lntd_fifo *readerp, lntd_fifo *writerp,
unsigned long flags)
{
if (flags != 0)
return LNTD_ERROR_INVALID_PARAMETER;
lntd_ko reader;
lntd_ko writer;
{
HANDLE xx;
HANDLE yy;
if (!CreatePipe(&xx, &yy, 0, 4096U)) {
lntd_error err =
HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
reader = xx;
writer = yy;
}
*readerp = reader;
*writerp = writer;
return 0;
}
lntd_error lntd_fifo_create(lntd_fifo *kop, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode)
{
return LNTD_ERROR_UNIMPLEMENTED;
}
|
mstewartgallus/linted | src/linted-init/init-posix.c | <reponame>mstewartgallus/linted<gh_stars>0
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/path.h"
#include "lntd/prctl.h"
#include "lntd/proc.h"
#include "lntd/signal.h"
#include "lntd/spawn.h"
#include "lntd/start.h"
#include "lntd/util.h"
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/wait.h>
static void delegate_signal(int signo);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-init",
.dont_init_signals = true};
static volatile sig_atomic_t monitor_pid = 0;
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err;
static int const exit_signals[] = {SIGHUP, SIGINT, SIGQUIT,
SIGTERM};
/* Delegate the exit signal to the monitor child */
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(exit_signals); ++ii) {
struct sigaction action = {0};
action.sa_handler = delegate_signal;
action.sa_flags = SA_RESTART;
sigfillset(&action.sa_mask);
if (-1 == sigaction(exit_signals[ii], &action, 0)) {
lntd_log(LNTD_LOG_ERROR, "sigaction: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
char const *monitor;
{
char *xx;
err = lntd_env_get("LINTED_MONITOR", &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
monitor = xx;
}
if (0 == monitor) {
lntd_log(LNTD_LOG_ERROR,
"%s is a required environment variable",
"LINTED_MONITOR");
return EXIT_FAILURE;
}
char *monitor_base;
{
char *xx;
err = lntd_path_base(&xx, monitor);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_path_base: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
monitor_base = xx;
}
err = lntd_prctl_set_child_subreaper(true);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_prctl_set_child_subreaper: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
struct lntd_spawn_attr *attr;
{
struct lntd_spawn_attr *xx;
err = lntd_spawn_attr_init(&xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_spawn_attr_init: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
attr = xx;
}
lntd_spawn_attr_set_die_on_parent_death(attr);
for (;;) {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: spawning %s\n", process_name,
monitor_base);
lntd_proc child;
{
lntd_proc xx;
err = lntd_spawn(
&xx, LNTD_KO_CWD, monitor, 0, attr,
(char const *const[]){monitor_base, 0}, 0);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_spawn: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
child = xx;
}
monitor_pid = child;
lntd_proc pid;
int code;
int status;
for (;;) {
{
siginfo_t info;
if (-1 ==
waitid(P_ALL, -1, &info, WEXITED))
goto waitid_failed;
pid = info.si_pid;
code = info.si_code;
status = info.si_status;
goto waitid_succeeded;
}
waitid_failed:
err = errno;
LNTD_ASSUME(err != 0);
if (EINTR == err)
continue;
LNTD_ASSERT(err != EINVAL);
LNTD_ASSERT(err != ECHILD);
LNTD_ASSERT(0 == err);
LNTD_ASSUME_UNREACHABLE();
waitid_succeeded:
if (child == pid)
break;
}
monitor_pid = 0;
switch (code) {
case CLD_EXITED:
/* Assume these errors are non-transient. */
lntd_io_write_format(LNTD_KO_STDERR, 0,
"monitor exited with %i\n",
status);
goto exit_loop;
case CLD_DUMPED:
case CLD_KILLED:
/* Assume these errors are transient and
* fixable by restarting. */
lntd_io_write_format(
LNTD_KO_STDERR, 0, "monitor killed by %s\n",
lntd_signal_string(status));
break;
default:
LNTD_ASSUME_UNREACHABLE();
}
}
exit_loop:
return EXIT_SUCCESS;
}
static void delegate_signal(int signo)
{
lntd_error old_err = errno;
lntd_error err = 0;
/* All signals are blocked here. */
lntd_proc the_pid = monitor_pid;
if (the_pid > 0U) {
/* If WNOHANG was specified in options and there were
* no children in a waitable state, then waitid()
* returns 0 immediately and the state of the
* siginfo_t structure pointed to by infop is
* unspecified.
*
* - WAIT(2) http://www.kernel.org/doc/man-pages/.
*/
{
siginfo_t info = {0};
if (-1 == waitid(P_PID, the_pid, &info,
WEXITED | WNOWAIT | WNOHANG))
err = errno;
if (ECHILD == err)
goto restore_errno;
if (err != 0) {
LNTD_ASSERT(err != EINTR);
LNTD_ASSERT(err != EINVAL);
LNTD_ASSERT(0 == err);
}
/* The process was killed and is waitable */
if (info.si_pid != 0)
goto restore_errno;
}
/* The process may be dead but not waited on at least */
kill(the_pid, signo);
}
restore_errno:
errno = old_err;
}
|
mstewartgallus/linted | include/lntd/proc.h | <reponame>mstewartgallus/linted
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_PID_H
#define LNTD_PID_H
#include "lntd/error.h"
#include <stddef.h>
#include <stdint.h>
#if defined HAVE_POSIX_API
typedef uintmax_t lntd_proc;
#else
/* `DWORD`s are 32-bit unsigned integers */
typedef uint_fast32_t lntd_proc;
#endif
/**
* @file
*
* System processes.
*/
#define LNTD_PID_COMM_MAX 16U
struct lntd_proc_stat {
lntd_proc pid;
char comm[LNTD_PID_COMM_MAX + 1U];
char state;
int ppid;
int pgrp;
int session;
int tty_nr;
int tpgid;
unsigned flags;
unsigned long minflt;
unsigned long cminflt;
unsigned long majflt;
unsigned long cmajflt;
unsigned long utime;
unsigned long stime;
long cutime;
long cstime;
long priority;
long nice;
long num_threads;
long itrealvalue;
unsigned long long starttime;
unsigned long vsize;
long rss;
unsigned long rsslim;
unsigned long startcode;
unsigned long endcode;
unsigned long startstack;
unsigned long kstkesp;
unsigned long kstkeip;
unsigned long signal;
unsigned long blocked;
unsigned long sigignore;
unsigned long sigcatch;
unsigned long wchan;
unsigned long nswap;
unsigned long cnswap;
int exit_signal;
int processor;
unsigned rt_priority;
unsigned policy;
unsigned long long delayacct_blkio_ticks;
unsigned long guest_time;
long cguest_time;
};
lntd_error lntd_proc_kill(lntd_proc pid, int signo);
lntd_error lntd_proc_terminate(lntd_proc pid);
lntd_error lntd_proc_continue(lntd_proc pid);
/**
* @warning The `comm` field is attacker controllable. See
* go-beyond.org/post/argv-for-no-fun-and-no-profit for
* potential problems naive display of it can cause. Not only
* could a process be named UTF-8 hackery but it could also use
* nondisplayable characters or even terminal control
* sequences.
*/
lntd_error lntd_proc_stat(lntd_proc pid, struct lntd_proc_stat *buf);
lntd_error lntd_proc_children(lntd_proc pid, lntd_proc **childrenp,
size_t *lenp);
lntd_proc lntd_proc_get_pid(void);
lntd_error lntd_proc_from_str(char const *str, lntd_proc *pidp);
lntd_error lntd_proc_name(char const *name);
#endif /* LNTD_PID_H */
|
mstewartgallus/linted | src/linted-control/linted-control.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/admin.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/locale.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/start.h"
#include "lntd/str.h"
#include "lntd/unit.h"
#include "lntd/util.h"
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
static uint_fast8_t run_status(char const *process_name, size_t argc,
char const *const argv[]);
static uint_fast8_t run_stop(char const *process_name, size_t argc,
char const *const argv[]);
static lntd_error ctl_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport);
static lntd_error status_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport);
static lntd_error stop_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport);
static lntd_error failure(lntd_ko ko, char const *process_name,
char const *message, lntd_error err);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-control", 0};
static unsigned char lntd_start_main(char const *const process_name,
size_t argc,
char const *const argv[])
{
bool need_help = false;
bool need_version = false;
char const *bad_option = 0;
char const *command = 0;
size_t last_index = 1U;
for (; last_index < argc; ++last_index) {
char const *argument = argv[last_index];
if (0 == strncmp(argument, "--", strlen("--"))) {
if (0 == strcmp(argument, "--help")) {
need_help = true;
} else if (0 == strcmp(argument, "--version")) {
need_version = true;
} else {
bad_option = argument;
}
} else {
command = argument;
break;
}
}
++last_index;
if (need_help) {
ctl_help(LNTD_KO_STDOUT, process_name, PACKAGE_NAME,
PACKAGE_URL, PACKAGE_BUGREPORT);
return EXIT_SUCCESS;
}
if (bad_option != 0) {
lntd_locale_on_bad_option(LNTD_KO_STDERR, process_name,
bad_option);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
if (need_version) {
lntd_locale_version(LNTD_KO_STDOUT, PACKAGE_STRING,
COPYRIGHT_YEAR);
return EXIT_SUCCESS;
}
if (0 == command) {
lntd_log(LNTD_LOG_ERROR, "missing COMMAND");
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
lntd_error err = 0;
char const *pid;
{
char *xx;
err = lntd_env_get("LINTED_PID", &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
pid = xx;
}
char const *runtime_dir_path;
{
char *xx;
err = lntd_env_get("XDG_RUNTIME_DIR", &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
runtime_dir_path = xx;
}
if (0 == pid) {
lntd_log(LNTD_LOG_ERROR,
"%s is a required environment variable",
"LINTED_PID");
return EXIT_FAILURE;
}
/**
* @todo Use fallbacks for missing XDG environment variables.
*/
if (0 == runtime_dir_path) {
lntd_log(LNTD_LOG_ERROR,
"%s is a required environment variable",
"XDG_RUNTIME_HOME");
return EXIT_FAILURE;
}
char *package_runtime_dir_path;
{
char *xx;
err = lntd_str_format(&xx, "%s/%s", runtime_dir_path,
PACKAGE_TARNAME);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_str_format: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
package_runtime_dir_path = xx;
}
char *process_runtime_dir_path;
{
char *xx;
err = lntd_str_format(&xx, "%s/%s",
package_runtime_dir_path, pid);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_str_format: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
process_runtime_dir_path = xx;
}
err = lntd_ko_change_directory(process_runtime_dir_path);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_change_directory: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
enum { STATUS, STOP };
static char const *const commands[] = {[STATUS] = "status",
[STOP] = "stop"};
int arg = -1;
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(commands); ++ii) {
if (0 == strcmp(command, commands[ii])) {
arg = ii;
break;
}
}
size_t new_argc = argc - last_index + 1U;
char const *const *new_argv = argv + last_index - 1U;
switch (arg) {
case STATUS:
return run_status(process_name, new_argc, new_argv);
case STOP:
return run_stop(process_name, new_argc, new_argv);
}
lntd_log(LNTD_LOG_ERROR, "urecognized command '%s'", command);
lntd_locale_try_for_more_help(LNTD_KO_STDERR, process_name,
"--help");
return EXIT_FAILURE;
}
static uint_fast8_t run_status(char const *process_name, size_t argc,
char const *const argv[])
{
lntd_error err;
bool need_version = false;
bool need_add_help = false;
char const *name = 0;
char const *bad_option = 0;
char const *bad_argument = 0;
size_t last_index = 1U;
for (; last_index < argc; ++last_index) {
char const *argument = argv[last_index];
if (0 == strncmp(argument, "--", strlen("--"))) {
if (0 == strcmp(argument, "--help")) {
need_add_help = true;
} else if (0 == strcmp(argument, "--version")) {
need_version = true;
} else {
bad_option = argument;
}
} else {
if (name != 0) {
bad_argument = argument;
break;
} else {
name = argument;
}
}
}
if (need_add_help) {
status_help(LNTD_KO_STDOUT, process_name, PACKAGE_NAME,
PACKAGE_URL, PACKAGE_BUGREPORT);
return EXIT_SUCCESS;
}
if (bad_option != 0) {
lntd_locale_on_bad_option(LNTD_KO_STDERR, process_name,
bad_option);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
if (bad_argument != 0) {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: too many arguments: '%s'\n",
process_name, bad_argument);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
if (need_version) {
lntd_locale_version(LNTD_KO_STDOUT, PACKAGE_STRING,
COPYRIGHT_YEAR);
return EXIT_SUCCESS;
}
if (0 == name) {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: missing SERVICE\n",
process_name);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
size_t name_len = strlen(name);
if (name_len > LNTD_UNIT_NAME_MAX) {
failure(LNTD_KO_STDERR, process_name, "SERVICE",
EINVAL);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
lntd_admin_in admin_in;
{
lntd_admin_in xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "admin-in",
LNTD_KO_WRONLY);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not create socket", err);
return EXIT_FAILURE;
}
admin_in = xx;
}
lntd_admin_out admin_out;
{
lntd_admin_out xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "admin-out",
LNTD_KO_RDONLY);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not create socket", err);
return EXIT_FAILURE;
}
admin_out = xx;
}
lntd_io_write_format(LNTD_KO_STDOUT, 0,
"%s: sending the status request for %s\n",
process_name, name);
{
struct lntd_admin_request request = {0};
request.type = LNTD_ADMIN_STATUS;
request.lntd_admin_request_u.status.name = (char *)name;
err = lntd_admin_in_send(admin_in, &request);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not send request", err);
return EXIT_FAILURE;
}
}
struct lntd_admin_reply reply;
err = lntd_admin_out_recv(admin_out, &reply);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not read reply", err);
return EXIT_FAILURE;
}
if (reply.lntd_admin_reply_u.status.is_up) {
lntd_io_write_format(LNTD_KO_STDOUT, 0,
"%s: %s is up\n", process_name,
name);
} else {
lntd_io_write_format(LNTD_KO_STDOUT, 0,
"%s: %s is down\n", process_name,
name);
}
return EXIT_SUCCESS;
}
static uint_fast8_t run_stop(char const *process_name, size_t argc,
char const *const *const argv)
{
lntd_error err;
bool need_version = false;
bool need_add_help = false;
char const *bad_option = 0;
char const *bad_argument = 0;
size_t last_index = 1U;
for (; last_index < argc; ++last_index) {
char const *argument = argv[last_index];
if (0 == strncmp(argument, "--", strlen("--"))) {
if (0 == strcmp(argument, "--help")) {
need_add_help = true;
} else if (0 == strcmp(argument, "--version")) {
need_version = true;
} else {
bad_option = argument;
}
} else {
bad_argument = argument;
break;
}
}
if (need_add_help) {
stop_help(LNTD_KO_STDOUT, process_name, PACKAGE_NAME,
PACKAGE_URL, PACKAGE_BUGREPORT);
return EXIT_SUCCESS;
}
if (bad_option != 0) {
lntd_locale_on_bad_option(LNTD_KO_STDERR, process_name,
bad_option);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
if (bad_argument != 0) {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: too many arguments: '%s'\n",
process_name, bad_argument);
lntd_locale_try_for_more_help(LNTD_KO_STDERR,
process_name, "--help");
return EXIT_FAILURE;
}
if (need_version) {
lntd_locale_version(LNTD_KO_STDOUT, PACKAGE_STRING,
COPYRIGHT_YEAR);
return EXIT_SUCCESS;
}
lntd_admin_in admin_in;
{
lntd_admin_in xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "admin-in",
LNTD_KO_WRONLY);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not create socket", err);
return EXIT_FAILURE;
}
admin_in = xx;
}
lntd_admin_out admin_out;
{
lntd_admin_out xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "admin-out",
LNTD_KO_RDONLY);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not create socket", err);
return EXIT_FAILURE;
}
admin_out = xx;
}
lntd_io_write_format(
LNTD_KO_STDOUT, 0,
"%s: sending the stop request for the gui\n", process_name);
{
struct lntd_admin_request request = {0};
request.type = LNTD_ADMIN_STOP;
request.lntd_admin_request_u.status.name = "linted-gui";
err = lntd_admin_in_send(admin_in, &request);
}
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can send request", err);
return EXIT_FAILURE;
}
bool was_up;
{
struct lntd_admin_reply xx;
err = lntd_admin_out_recv(admin_out, &xx);
if (err != 0) {
failure(LNTD_KO_STDERR, process_name,
"can not read reply", err);
return EXIT_FAILURE;
}
was_up = xx.lntd_admin_reply_u.stop.was_up;
}
if (was_up) {
lntd_io_write_format(LNTD_KO_STDOUT, 0,
"%s: gui was killed\n",
process_name);
} else {
lntd_io_write_format(LNTD_KO_STDOUT, 0,
"%s: the gui was not killed\n",
process_name);
}
return EXIT_SUCCESS;
}
static lntd_error ctl_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport)
{
lntd_error err;
size_t size = 0U;
size_t cap = 0U;
char *buf = 0;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
Usage: ");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, process_name);
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
[OPTIONS]\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
Run the admin program.\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
--help display this help and exit\n\
--version display version information and exit\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
status request the status of the service\n\
stop stop the gui service\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
Report bugs to <");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size,
package_bugreport);
if (err)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, ">\n");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, package_name);
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, "\
home page: <");
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, package_url);
if (err != 0)
goto free_buf;
err = lntd_str_append_cstring(&buf, &cap, &size, ">\n");
if (err != 0)
goto free_buf;
err = lntd_io_write_all(ko, 0, buf, size);
if (err != 0)
goto free_buf;
free_buf:
lntd_mem_free(buf);
return err;
}
static lntd_error status_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport)
{
lntd_error err;
err = lntd_io_write_string(ko, 0,
"Usage: LNTD_ADMIN_SOCKET=SOCKET ");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, process_name);
if (err != 0)
return err;
err =
lntd_io_write_string(ko, 0, " status [OPTIONS] SERVICE\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\
Report the status.\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\
--help display this help and exit\n\
--version display version information and exit\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\
SOCKET the socket to connect to\n\
SERVICE the service to get the status of\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "Report bugs to <");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_bugreport);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ">\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_name);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, " home page: <");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_url);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ">\n");
if (err != 0)
return err;
return 0;
}
static lntd_error stop_help(lntd_ko ko, char const *process_name,
char const *package_name,
char const *package_url,
char const *package_bugreport)
{
lntd_error err;
err = lntd_io_write_string(ko, 0,
"Usage: LNTD_ADMIN_SOCKET=SOCKET ");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, process_name);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, " stop [OPTIONS]\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "Stop a service.\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\
--help display this help and exit\n\
--version display version information and exit\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\
SOCKET the socket to connect to\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "Report bugs to <");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_bugreport);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ">\n");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_name);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, " home page: <");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, package_url);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ">\n");
if (err != 0)
return err;
return 0;
}
static lntd_error failure(lntd_ko ko, char const *process_name,
char const *message, lntd_error error)
{
lntd_error err;
err = lntd_io_write_string(ko, 0, process_name);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ": ");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, message);
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, ": ");
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, lntd_error_string(error));
if (err != 0)
return err;
err = lntd_io_write_string(ko, 0, "\n");
if (err != 0)
return err;
return 0;
}
|
mstewartgallus/linted | src/log/log-posix.c | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/util.h"
#include <stdarg.h>
#include <stdbool.h>
#include <syslog.h>
static lntd_ko tty;
static bool tty_init;
static void do_syslog(int prio, char const *format, va_list args)
LNTD_FORMAT(__printf__, 2, 0);
void lntd_log_open(char const *ident)
{
/* For now, don't use LOG_PID because syslog is confused by
* CLONE_NEWPID.
*/
openlog(ident, LOG_CONS | LOG_NDELAY, LOG_USER);
if (0 ==
lntd_ko_open(&tty, LNTD_KO_CWD, "/dev/tty", LNTD_KO_WRONLY))
tty_init = true;
}
void lntd_log(lntd_log_level log_level, char const *format, ...)
{
int priority;
switch (log_level) {
case LNTD_LOG_ERROR:
priority = LOG_ERR;
break;
case LNTD_LOG_WARNING:
priority = LOG_WARNING;
break;
case LNTD_LOG_INFO:
priority = LOG_INFO;
break;
default:
LNTD_ASSERT(false);
return;
}
va_list ap;
va_start(ap, format);
do_syslog(priority, format, ap);
if (tty_init) {
lntd_io_write_va_list(tty, 0, format, ap);
lntd_io_write_string(tty, 0, "\n");
}
va_end(ap);
}
static void do_syslog(int prio, char const *format, va_list args)
{
va_list cp;
va_copy(cp, args);
vsyslog(prio, format, cp);
va_end(cp);
}
|
mstewartgallus/linted | include/lntd/file.h | /*
* Copyright 2014 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_FILE_H
#define LNTD_FILE_H
#include "lntd/error.h"
#include "lntd/ko.h"
#include <sys/types.h>
/**
* @file
*
* Abstracts over the concept of a regular filesystem file.
*/
typedef lntd_ko lntd_file;
#define LNTD_FILE_RDONLY 1UL
#define LNTD_FILE_WRONLY (1UL << 1U)
#define LNTD_FILE_RDWR (1UL << 2U)
#define LNTD_FILE_SYNC (1UL << 3U)
#define LNTD_FILE_EXCL (1UL << 4U)
lntd_error lntd_file_create(lntd_file *filep, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode);
#endif /* LNTD_FILE_H */
|
mstewartgallus/linted | src/start/start-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#define LNTD_START__NO_MAIN 1
#include "lntd/start.h"
#include "lntd/async.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/signal.h"
#include "lntd/util.h"
#include <dirent.h>
#include <errno.h>
#include <locale.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined HAVE_SYS_AUXV_H
#include <sys/auxv.h>
#endif
static void do_nothing(int signo);
static lntd_error open_standard_handles(void);
static lntd_error privilege_check(void);
static lntd_error sanitize_fds(void);
int lntd_start__main(struct lntd_start_config const *config,
unsigned char (*start)(char const *process_name,
size_t argc,
char const *const argv[]),
int argc, char **argv)
{
lntd_error err = 0;
err = open_standard_handles();
if (err != 0) {
return EXIT_FAILURE;
}
char const *process_name = 0;
bool missing_name = false;
char const *service;
{
char *xx;
err = lntd_env_get("LINTED_SERVICE", &xx);
if (err != 0)
return EXIT_FAILURE;
service = xx;
}
if (service != 0) {
process_name = service;
} else if (argc > 0) {
process_name = argv[0U];
} else {
process_name = config->canonical_process_name;
missing_name = true;
}
char *process_basename;
{
char *xx;
err = lntd_path_base(&xx, process_name);
if (err != 0)
return EXIT_FAILURE;
process_basename = xx;
}
if (config->sanitize_fds) {
err = sanitize_fds();
if (err != 0)
return err;
}
lntd_log_open(process_basename);
if (missing_name) {
lntd_log(LNTD_LOG_ERROR, "missing process name");
return EXIT_FAILURE;
}
if (config->check_privilege) {
err = privilege_check();
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "privilege_check: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
{
struct sigaction act = {0};
sigemptyset(&act.sa_mask);
act.sa_handler = do_nothing;
act.sa_flags = 0;
if (-1 == sigaction(LNTD_ASYNCH_SIGNO, &act, 0)) {
lntd_log(LNTD_LOG_ERROR, "sigaction: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
}
if (!config->dont_init_signals) {
err = lntd_signal_init();
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_signal_init: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
if (0 == setlocale(LC_ALL, "")) {
lntd_log(LNTD_LOG_ERROR, "setlocale: %s",
lntd_error_string(errno));
return EXIT_FAILURE;
}
tzset();
return start(process_basename, argc, (char const *const *)argv);
}
static void do_nothing(int signo)
{
/* Do nothing */
}
static lntd_error open_standard_handles(void)
{
lntd_error err = 0;
for (;;) {
lntd_ko ko;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD,
"/dev/null", LNTD_KO_RDWR);
if (err != 0)
break;
ko = xx;
}
if (ko > 2U) {
err = lntd_ko_close(ko);
break;
}
}
return err;
}
static lntd_error privilege_check(void)
{
uid_t uid = getuid();
if (0 == uid)
return EPERM;
gid_t gid = getgid();
if (0 == gid)
return EPERM;
#if defined HAVE_SYS_AUXV_H && defined HAVE_GETAUXVAL && \
defined AT_SECURE
if (getauxval(AT_SECURE))
return EPERM;
#endif
return 0;
}
static lntd_error sanitize_fds(void)
{
lntd_error err = 0;
lntd_ko fds_dir_ko;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD,
"/proc/thread-self/fd",
LNTD_KO_DIRECTORY);
if (err != 0)
return err;
fds_dir_ko = xx;
}
DIR *fds_dir = fdopendir(fds_dir_ko);
if (0 == fds_dir) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(fds_dir_ko);
return err;
}
lntd_ko *kos_to_close = 0;
size_t num_kos_to_close = 0U;
/* Read all the open fds first and then close the fds
* after because otherwise there is a race condition */
for (;;) {
errno = 0;
struct dirent *direntry = readdir(fds_dir);
if (0 == direntry) {
err = errno;
break;
}
char const *fdname = direntry->d_name;
if (0 == strcmp(".", fdname))
continue;
if (0 == strcmp("..", fdname))
continue;
lntd_ko open_fd = (lntd_ko)atoi(fdname);
if (0U == open_fd)
continue;
if (1U == open_fd)
continue;
if (2U == open_fd)
continue;
if (fds_dir_ko == open_fd)
continue;
{
void *xx;
err = lntd_mem_realloc_array(
&xx, kos_to_close, num_kos_to_close + 1U,
sizeof kos_to_close[0U]);
if (err != 0)
break;
kos_to_close = xx;
}
kos_to_close[num_kos_to_close] = open_fd;
++num_kos_to_close;
}
if (-1 == closedir(fds_dir)) {
err = errno;
LNTD_ASSUME(err != 0);
}
/* Deliberately don't check the closed fds */
for (size_t ii = 0U; ii < num_kos_to_close; ++ii)
lntd_ko_close(kos_to_close[ii]);
lntd_mem_free(kos_to_close);
return err;
}
|
mstewartgallus/linted | include/lntd/str.h | <reponame>mstewartgallus/linted<gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_STR_H
#define LNTD_STR_H
#include "lntd/error.h"
#include "lntd/util.h"
#include <stddef.h>
/**
* @file
*
*/
lntd_error lntd_str_dup(char **result, char const *input);
lntd_error lntd_str_dup_len(char **result, char const *input, size_t n);
lntd_error lntd_str_append(char **bufp, size_t *capp, size_t *sizep,
char const *str, size_t strsize);
lntd_error lntd_str_append_cstring(char **bufp, size_t *capp,
size_t *sizep, char const *str);
lntd_error lntd_str_append_format(char **bufp, size_t *capp,
size_t *sizep, char const *formatstr,
...) LNTD_FORMAT(__printf__, 4, 5);
lntd_error lntd_str_format(char **strp, char const *format, ...)
LNTD_FORMAT(__printf__, 2, 3);
#endif /* LNTD_STR_H */
|
mstewartgallus/linted | include/lntd/ko.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_KO_H
#define LNTD_KO_H
#include "lntd/error.h"
#include "lntd/util.h"
#if defined HAVE_WINDOWS_API
#include "ko-windows.h"
#elif defined HAVE_POSIX_API
#include "ko-posix.h"
#else
#error kernel object support has not beeen implemented for this platform
#endif
/**
* @file
*
* Abstracts over the concept of a kernel object.
*/
#define LNTD_KO_RDONLY 1UL
#define LNTD_KO_WRONLY (1UL << 1U)
#define LNTD_KO_RDWR (1UL << 2U)
#define LNTD_KO_APPEND (1UL << 3U)
#define LNTD_KO_SYNC (1UL << 4U)
#define LNTD_KO_DIRECTORY (1UL << 5U)
#define LNTD_KO_FIFO (1UL << 6U)
lntd_error lntd_ko_open(lntd_ko *kop, lntd_ko dirko,
char const *pathname,
unsigned long flags) LNTD_WARN_UNUSED;
/**
* The lntd_ko_close function closes a kernel object.
*
* @param ko The kernel object to close.
*
* @returns Zero on success or an error code.
*
* @error EIO I/O error.
*
* @error EBADF Not a valid file descriptor.
*/
lntd_error lntd_ko_close(lntd_ko ko);
lntd_error lntd_ko_change_directory(char const *pathname);
lntd_error lntd_ko_symlink(char const *oldpath, char const *newpath);
lntd_error lntd_ko_real_path(char **resultp, lntd_ko dirko,
char const *pathname) LNTD_WARN_UNUSED;
#endif /* LNTD_KO_H */
|
mstewartgallus/linted | src/io/io-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE 200809L
#include "config.h"
#include "lntd/io.h"
#include "lntd/async.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
/* Android's libc does not have the pthread_sigmask declaration in
* signal.h as mandated by POSIX. */
#if defined __BIONIC__
#include <pthread.h>
#endif
#if defined __BIONIC__
#include <sys/syscall.h>
#endif
struct lntd_io_task_poll {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
lntd_ko ko;
short events;
short revents;
};
struct lntd_io_task_read {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
char *buf;
size_t size;
size_t current_position;
size_t bytes_read;
lntd_ko ko;
};
struct lntd_io_task_write {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
char const *buf;
size_t size;
size_t current_position;
size_t bytes_wrote;
lntd_ko ko;
};
static sigset_t get_pipe_set(void);
static lntd_error eat_sigpipes(void);
static lntd_error poll_one(lntd_ko ko, short events, short *revents);
static lntd_error check_for_poll_error(short revents);
lntd_error lntd_io_read_all(lntd_ko ko, size_t *bytes_read_out,
void *buf, size_t size)
{
size_t bytes_read = 0U;
size_t bytes_left = size;
char *buf_offset = buf;
lntd_error err = 0;
restart_reading:
;
ssize_t result = read(ko, buf_offset, bytes_left);
if (result < 0) {
err = errno;
LNTD_ASSUME(err != 0);
if (EINTR == err)
goto restart_reading;
if (EAGAIN == err)
goto poll_for_readability;
if (EWOULDBLOCK == err)
goto poll_for_readability;
return err;
}
size_t bytes_read_delta = result;
if (0U == bytes_read_delta)
goto finish_reading;
buf_offset += bytes_read_delta;
bytes_read += bytes_read_delta;
bytes_left -= bytes_read_delta;
if (bytes_left != 0)
goto restart_reading;
finish_reading:
if (bytes_read_out != 0)
*bytes_read_out = bytes_read;
return err;
poll_for_readability:
;
short revents;
{
short xx;
err = poll_one(ko, POLLIN, &xx);
if (EINTR == err)
goto poll_for_readability;
if (EAGAIN == err)
goto poll_for_readability;
if (err != 0)
goto finish_reading;
revents = xx;
}
err = check_for_poll_error(revents);
if (err != 0)
goto finish_reading;
if ((revents & POLLIN) != 0)
goto restart_reading;
if ((revents & POLLHUP) != 0)
goto finish_reading;
LNTD_ASSUME_UNREACHABLE();
}
lntd_error lntd_io_write_all(lntd_ko ko, size_t *bytes_wrote_out,
void const *buf, size_t size)
{
lntd_error err = 0;
size_t bytes_wrote = 0U;
size_t bytes_left = size;
char const *buf_offset = buf;
{
sigset_t oldset;
/* Get EPIPEs */
/* SIGPIPE may not be blocked already */
/* Reuse oldset to save on stack space */
sigemptyset(&oldset);
sigaddset(&oldset, SIGPIPE);
err = pthread_sigmask(SIG_BLOCK, &oldset, &oldset);
if (err != 0)
goto write_bytes_wrote;
for (;;) {
ssize_t result =
write(ko, buf_offset, bytes_left);
if (-1 == result) {
err = errno;
LNTD_ASSUME(err != 0);
if (EINTR == err)
continue;
if (EAGAIN == err)
goto poll_for_writeability;
break;
}
size_t bytes_wrote_delta = result;
buf_offset += bytes_wrote_delta;
bytes_wrote += bytes_wrote_delta;
bytes_left -= bytes_wrote_delta;
if (bytes_left != 0)
continue;
break;
poll_for_writeability:
;
short revents;
{
short xx;
err = poll_one(ko, POLLOUT, &xx);
if (EINTR == err)
goto poll_for_writeability;
if (EAGAIN == err)
goto poll_for_writeability;
if (err != 0)
break;
revents = xx;
}
err = check_for_poll_error(revents);
if (err != 0)
break;
if ((revents & POLLOUT) != 0)
continue;
LNTD_ASSUME_UNREACHABLE();
}
/* Consume SIGPIPEs */
lntd_error eat_err = eat_sigpipes();
if (0 == err)
err = eat_err;
lntd_error mask_err =
pthread_sigmask(SIG_SETMASK, &oldset, 0);
if (0 == err)
err = mask_err;
goto write_bytes_wrote;
}
write_bytes_wrote:
if (bytes_wrote_out != 0)
*bytes_wrote_out = bytes_wrote;
return err;
}
lntd_error lntd_io_write_string(lntd_ko ko, size_t *bytes_wrote_out,
char const *s)
{
return lntd_io_write_all(ko, bytes_wrote_out, s, strlen(s));
}
lntd_error lntd_io_write_format(lntd_ko ko, size_t *bytes_wrote_out,
char const *format_str, ...)
{
va_list ap;
va_start(ap, format_str);
lntd_error err =
lntd_io_write_va_list(ko, bytes_wrote_out, format_str, ap);
va_end(ap);
return err;
}
lntd_error lntd_io_write_va_list(lntd_ko ko, size_t *bytes_wrote_out,
char const *format_str, va_list list)
{
lntd_error err = 0;
int bytes;
{
sigset_t oldset;
/* Get EPIPEs */
/* SIGPIPE may not be blocked already */
/* Reuse oldset to save on stack space */
sigemptyset(&oldset);
sigaddset(&oldset, SIGPIPE);
err = pthread_sigmask(SIG_BLOCK, &oldset, &oldset);
if (err != 0)
return err;
#if defined __BIONIC__
bytes = vfdprintf(ko, format_str, list);
#else
bytes = vdprintf(ko, format_str, list);
#endif
if (bytes < 0) {
err = errno;
LNTD_ASSUME(err != 0);
}
lntd_error eat_err = eat_sigpipes();
if (0 == err)
err = eat_err;
lntd_error mask_err =
pthread_sigmask(SIG_SETMASK, &oldset, 0);
if (0 == err)
err = mask_err;
}
if (err != 0)
return err;
if (bytes_wrote_out != 0)
*bytes_wrote_out = bytes;
return 0;
}
static lntd_error poll_one(lntd_ko ko, short events, short *reventsp)
{
lntd_error err;
short revents;
{
struct pollfd pollfd = {.fd = ko, .events = events};
int poll_status = poll(&pollfd, 1U, -1);
if (-1 == poll_status)
goto poll_failed;
revents = pollfd.revents;
goto poll_succeeded;
}
poll_failed:
err = errno;
LNTD_ASSUME(err != 0);
return err;
poll_succeeded:
*reventsp = revents;
return 0;
}
static lntd_error check_for_poll_error(short revents)
{
lntd_error err = 0;
if ((revents & POLLNVAL) != 0)
err = EBADF;
return err;
}
lntd_error lntd_io_task_poll_create(struct lntd_io_task_poll **taskp,
void *data)
{
lntd_error err;
struct lntd_io_task_poll *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(&xx, task,
LNTD_ASYNCH_TASK_POLL);
if (err != 0)
goto free_task;
parent = xx;
}
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
task->waiter = xx;
}
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_parent:
lntd_mem_free(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_io_task_poll_destroy(struct lntd_io_task_poll *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_io_task_poll_submit(struct lntd_async_pool *pool,
struct lntd_io_task_poll *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko ko, int flags)
{
task->ko = ko;
task->events = flags;
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
void *lntd_io_task_poll_data(struct lntd_io_task_poll *task)
{
return task->data;
}
lntd_error lntd_io_task_read_create(struct lntd_io_task_read **taskp,
void *data)
{
lntd_error err;
struct lntd_io_task_read *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(&xx, task,
LNTD_ASYNCH_TASK_READ);
if (err != 0)
goto free_task;
parent = xx;
}
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
task->waiter = xx;
}
task->parent = parent;
task->data = data;
task->current_position = 0U;
*taskp = task;
return 0;
free_parent:
lntd_mem_free(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_io_task_read_destroy(struct lntd_io_task_read *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_io_task_read_submit(struct lntd_async_pool *pool,
struct lntd_io_task_read *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko ko, char *buf,
size_t size)
{
task->ko = ko;
task->buf = buf;
task->size = size;
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
struct lntd_async_task *
lntd_io_task_read_to_async(struct lntd_io_task_read *task)
{
return task->parent;
}
void *lntd_io_task_read_data(struct lntd_io_task_read *task)
{
return task->data;
}
lntd_ko lntd_io_task_read_ko(struct lntd_io_task_read *task)
{
return task->ko;
}
size_t lntd_io_task_read_bytes_read(struct lntd_io_task_read *task)
{
return task->bytes_read;
}
lntd_error lntd_io_task_write_create(struct lntd_io_task_write **taskp,
void *data)
{
lntd_error err;
struct lntd_io_task_write *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(&xx, task,
LNTD_ASYNCH_TASK_WRITE);
if (err != 0)
goto free_task;
parent = xx;
}
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
task->waiter = xx;
}
task->parent = parent;
task->data = data;
task->current_position = 0U;
*taskp = task;
return 0;
free_parent:
lntd_async_task_destroy(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_io_task_write_destroy(struct lntd_io_task_write *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_io_task_read_cancel(struct lntd_io_task_read *task)
{
lntd_async_task_cancel(task->parent);
}
void lntd_io_task_write_cancel(struct lntd_io_task_write *task)
{
lntd_async_task_cancel(task->parent);
}
void lntd_io_task_write_submit(struct lntd_async_pool *pool,
struct lntd_io_task_write *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko ko,
char const *buf, size_t size)
{
task->ko = ko;
task->buf = buf;
task->size = size;
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
void *lntd_io_task_write_data(struct lntd_io_task_write *task)
{
return task->data;
}
void lntd_io_do_poll(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_io_task_poll *task_poll =
lntd_async_task_data(task);
struct lntd_async_waiter *waiter = task_poll->waiter;
lntd_ko ko = task_poll->ko;
short events = task_poll->events;
short revents = lntd_async_waiter_revents(waiter);
if (0 == revents) {
lntd_async_pool_wait_on_poll(pool, waiter, task, ko,
events);
return;
}
task_poll->revents = revents;
lntd_async_pool_complete(pool, task, 0);
}
void lntd_io_do_read(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_io_task_read *task_read =
lntd_async_task_data(task);
size_t bytes_read = task_read->current_position;
size_t bytes_left = task_read->size - bytes_read;
lntd_ko ko = task_read->ko;
char *buf = task_read->buf;
struct lntd_async_waiter *waiter = task_read->waiter;
lntd_error err = 0;
ssize_t result = read(ko, buf + bytes_read, bytes_left);
if (result < 0) {
err = errno;
LNTD_ASSUME(err != 0);
}
if (EINTR == err)
goto submit_retry;
if (EAGAIN == err || EWOULDBLOCK == err)
goto wait_on_poll;
if (err != 0)
goto complete_task;
/* Hangup or nothing more to read */
if (0 == result)
goto complete_task;
size_t bytes_read_delta = result;
bytes_read += bytes_read_delta;
bytes_left -= bytes_read_delta;
if (bytes_read_delta != 0U && bytes_left != 0U)
goto submit_retry;
complete_task:
task_read->bytes_read = bytes_read;
task_read->current_position = 0U;
lntd_async_pool_complete(pool, task, err);
return;
submit_retry:
task_read->bytes_read = bytes_read;
task_read->current_position = bytes_read;
lntd_async_pool_resubmit(pool, task);
return;
wait_on_poll:
lntd_async_pool_wait_on_poll(pool, waiter, task, ko, POLLIN);
}
void lntd_io_do_write(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_io_task_write *task_write =
lntd_async_task_data(task);
size_t bytes_wrote = task_write->current_position;
size_t bytes_left = task_write->size - bytes_wrote;
lntd_error err = 0;
lntd_ko ko = task_write->ko;
char const *buf = task_write->buf;
char const *buf_offset = buf + bytes_wrote;
/* We can assume that SIGPIPEs are blocked here. */
ssize_t result = write(ko, buf_offset, bytes_left);
if (-1 == result) {
err = errno;
LNTD_ASSUME(err != 0);
}
if (EINTR == err)
goto submit_retry;
if (EAGAIN == err || EWOULDBLOCK == err)
goto wait_on_poll;
if (err != 0)
goto complete_task;
size_t bytes_wrote_delta = result;
bytes_wrote += bytes_wrote_delta;
bytes_left -= bytes_wrote_delta;
if (bytes_left != 0U)
goto submit_retry;
complete_task:
task_write->bytes_wrote = bytes_wrote;
task_write->current_position = 0U;
lntd_async_pool_complete(pool, task, err);
return;
submit_retry:
task_write->bytes_wrote = bytes_wrote;
task_write->current_position = bytes_wrote;
lntd_async_pool_resubmit(pool, task);
return;
wait_on_poll:
lntd_async_pool_wait_on_poll(pool, task_write->waiter, task, ko,
POLLOUT);
}
static struct timespec const zero_timeout = {0};
static lntd_error eat_sigpipes(void)
{
lntd_error err = 0;
for (;;) {
int wait_status;
sigset_t const pipe_set = get_pipe_set();
struct timespec const *timeoutp = &zero_timeout;
#if defined __BIONIC__
wait_status = syscall(__NR_rt_sigtimedwait, &pipe_set,
0, timeoutp);
#else
wait_status = sigtimedwait(&pipe_set, 0, timeoutp);
#endif
if (wait_status != -1)
continue;
lntd_error wait_err = errno;
LNTD_ASSUME(wait_err != 0);
if (EAGAIN == wait_err)
break;
if (wait_err != EINTR) {
if (0 == err)
err = wait_err;
break;
}
}
return err;
}
static sigset_t get_pipe_set(void)
{
sigset_t pipeset;
sigemptyset(&pipeset);
sigaddset(&pipeset, SIGPIPE);
return pipeset;
}
|
mstewartgallus/linted | src/linted-window/linted-window-windows.c | <reponame>mstewartgallus/linted
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#define COBJMACROS
#include "config.h"
#include "lntd/start.h"
#include "lntd/error.h"
#include "lntd/log.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <d3d9.h>
#include <windows.h>
typedef WINAPI IDirect3D9 *typeof_Direct3DCreate9(UINT SDKVersion);
static GUID const uuidof_IDXGIDevice = {
0x54ec77fa,
0x1377,
0x44e6,
{0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}};
static GUID const uuidof_IDXGIFactory1 = {
0x770aae78,
0xf26f,
0x4dba,
{0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87}};
static HINSTANCE get_current_module(void)
{
static char const dummy;
HINSTANCE xx;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(void *)&dummy, &xx);
return xx;
}
static LRESULT CALLBACK window_procedure(HWND, UINT, WPARAM, LPARAM);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-window", 0};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
HGDIOBJ arrow_cursor = LoadCursor(0, IDC_ARROW);
if (0 == arrow_cursor) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto report_exit_status;
}
HGDIOBJ white_brush = GetStockObject(WHITE_BRUSH);
if (0 == white_brush) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto report_exit_status;
}
ATOM class_atom;
{
WNDCLASS window_class = {0};
window_class.lpfnWndProc = window_procedure;
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.hInstance = get_current_module();
window_class.hCursor = arrow_cursor;
window_class.hbrBackground = white_brush;
window_class.lpszClassName =
L"" PACKAGE_NAME_SPACE ".MainWindowClass";
class_atom = RegisterClass(&window_class);
}
if (0 == class_atom) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto report_exit_status;
}
HWND main_window = CreateWindowEx(
WS_EX_APPWINDOW | WS_EX_COMPOSITED,
(LPCTSTR)(uintptr_t)class_atom, L"" PACKAGE_NAME,
WS_OVERLAPPED | WS_CAPTION | WS_THICKFRAME |
WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
0, 0, get_current_module(), 0);
if (0 == main_window) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto destroy_window;
}
switch (ShowWindow(main_window, lntd_start_show_command())) {
case -1: {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto destroy_window;
}
case 0:
default:
break;
}
HMODULE d3d9_module = LoadLibraryW(L"d3d9.dll");
if (0 == d3d9_module) {
lntd_log(LNTD_LOG_ERROR, "Could not find d3d9.dll");
return EXIT_FAILURE;
}
SetLastError(0);
typeof_Direct3DCreate9 *my_Direct3dCreate9 =
(typeof_Direct3DCreate9 *)GetProcAddress(d3d9_module,
"Direct3DCreate9");
err = HRESULT_FROM_WIN32(GetLastError());
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "GetProcAddress: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
IDirect3D9 *direct3d = my_Direct3dCreate9(D3D_SDK_VERSION);
if (0 == direct3d) {
lntd_log(LNTD_LOG_ERROR, "Direct3dCreate9");
err = LNTD_ERROR_UNIMPLEMENTED;
goto destroy_window;
}
IDirect3DDevice9 *device;
{
D3DPRESENT_PARAMETERS xx = {0};
IDirect3DDevice9 *yy;
xx.BackBufferFormat = D3DFMT_UNKNOWN;
xx.MultiSampleType = D3DMULTISAMPLE_NONE;
xx.SwapEffect = D3DSWAPEFFECT_FLIP;
xx.hDeviceWindow = main_window;
xx.Windowed = true;
xx.EnableAutoDepthStencil = true;
xx.AutoDepthStencilFormat = D3DFMT_R8G8B8;
xx.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
err = IDirect3D9_CreateDevice(
direct3d, D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
main_window, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&xx, &yy);
if (FAILED(err))
goto destroy_direct3d;
device = yy;
}
if (0 == UpdateWindow(main_window)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto destroy_device;
}
for (;;) {
for (;;) {
MSG message;
switch (
PeekMessage(&message, 0, 0, 0, PM_REMOVE)) {
case -1:
return -1;
case 0:
goto exit_peek_loop;
default:
if (WM_QUIT == message.message) {
err = message.wParam;
goto destroy_device;
}
if (-1 == TranslateMessage(&message)) {
err = HRESULT_FROM_WIN32(
GetLastError());
goto destroy_device;
}
DispatchMessage(&message);
break;
}
}
exit_peek_loop:
err = IDirect3DDevice9_Clear(
device, 0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_ARGB(255, 0, 255, 255), 0, 0);
if (FAILED(err))
goto destroy_device;
err = IDirect3DDevice9_Present(device, 0, 0,
main_window, 0);
if (FAILED(err))
goto destroy_device;
}
destroy_device:
IDirect3DDevice9_Release(device);
destroy_direct3d:
IDirect3D9_Release(direct3d);
destroy_window:
/* In this case the window has not already been destroyed */
if (err != 0) {
DestroyWindow(main_window);
for (;;) {
MSG message;
switch (
PeekMessage(&message, 0, 0, 0, PM_REMOVE)) {
case -1:
case 0:
goto window_destroyed;
default:
DispatchMessage(&message);
break;
}
}
}
window_destroyed:
report_exit_status:
if (FAILED(err))
lntd_log(LNTD_LOG_ERROR, "%s", lntd_error_string(err));
return err;
}
static LRESULT on_paint(HWND main_window, UINT message_type,
WPARAM w_param, LPARAM l_param);
static LRESULT on_destroy(HWND main_window, UINT message_type,
WPARAM w_param, LPARAM l_param);
static LRESULT CALLBACK window_procedure(HWND main_window,
UINT message_type,
WPARAM w_param, LPARAM l_param)
{
switch (message_type) {
case WM_PAINT:
return on_paint(main_window, message_type, w_param,
l_param);
case WM_DESTROY:
return on_destroy(main_window, message_type, w_param,
l_param);
default:
return DefWindowProc(main_window, message_type, w_param,
l_param);
}
}
static LRESULT on_paint(HWND main_window, UINT message_type,
WPARAM w_param, LPARAM l_param)
{
DWORD err = 0;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(main_window, &ps);
if (0 == hdc) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
goto post_quit_message;
}
if (0 == EndPaint(main_window, &ps)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSERT(err != 0);
}
post_quit_message:
if (err != 0)
PostQuitMessage(err);
return 0;
}
static LRESULT on_destroy(HWND main_window, UINT message_type,
WPARAM w_param, LPARAM l_param)
{
PostQuitMessage(0);
return DefWindowProc(main_window, message_type, w_param,
l_param);
}
|
mstewartgallus/linted | src/error/error-posix.c | <filename>src/error/error-posix.c
/*
* Copyright 2013, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200112L
#include "config.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <string.h>
static char const invalid_error_string[] = "invalid error number";
static char const out_of_memory_string[] =
"cannot print error, out of memory";
char const *lntd_error_string(lntd_error err_to_print)
{
if (err_to_print > INT_MAX)
return invalid_error_string;
lntd_error err;
char *buf = 0;
size_t buf_size = 0U;
for (;;) {
buf_size = 2U * buf_size + 1U;
{
void *xx;
err = lntd_mem_realloc(&xx, buf, buf_size);
if (err != 0)
break;
buf = xx;
}
err = strerror_r(err_to_print, buf, buf_size);
if (0 == err)
break;
if (err != ERANGE)
break;
}
if (0 == err) {
void *xx;
err = lntd_mem_realloc(&xx, buf, strlen(buf) + 1U);
if (0 == err)
buf = xx;
}
if (err != 0)
lntd_mem_free(buf);
switch (err) {
case 0:
return buf;
case EINVAL:
return invalid_error_string;
case ENOMEM:
return out_of_memory_string;
default:
LNTD_ASSUME_UNREACHABLE();
}
}
void lntd_error_string_free(char const *str)
{
if (invalid_error_string == str)
return;
if (out_of_memory_string == str)
return;
lntd_mem_free((char *)str);
}
|
mstewartgallus/linted | docs/coding.h | /* Copyright (C) 2014 <NAME>
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty provided
* the copyright notice and this notice are preserved.
*/
/**
@file
Linted -- Coding Standards
This is a list of standards for maintaining correct and high quality
code in Linted. It is more important to understand the coding standard
than to follow it.
The Linted project unconditionally enforces its rules for correct code.
No exceptions.
The Linted project has rules that may help ensure high code quality,
that is to say: functional and defect-free code. However, these code
quality rules are only heuristics and should never get in the way of
writing correct code.
The Linted project's rules for code style are nothing more than
guidelines.
@section correctness Code Correctness
<ul>
<li> Honestly reassess one's own competence.
Don't do security theater and don't do cargo cult security. Use simple,
understandable and secure methods of making one's code correct. If you
can't prove the code is correct it's not.
</li>
<li> Do not leak private data to other actors.
For example, when one copies data from structures to external sources
using `mq_send`, `write` or other functions as if they are byte arrays
one can leak data through data structure padding. See also CERT rule
DCL39-C: Avoid information leakage in structure padding (as of
2014-02-15 available at
https://www.securecoding.cert.org/confluence/display/seccode/DCL39-C.+Avoid+information+leakage+in+structure+padding
).
</li>
<li> Do not leak capabilities or privileges to other actors.
For example, when one spawns a new sandboxed process one should not
leave open extraneous file descriptors and so leak privileges to the new
process.
</li>
<li> Properly recover from and report function failure.
A function may fail at accomplishing it's task. This failure is not an
error, incorrect code, a rare event or unexpected. In the event of
failure to accomplish a task, the task must be retried, an alternative
must be tried or the task must sanely exit. In the event of a failure
to accomplish a task no corruption of task state is expected.
</li>
<li> Abort <strong>as soon as possible</strong> on finding errorneous
task state.
A task may have unexpected and erroneous state that violates internal
assertions. Such state implies that the task's code was written
incorrectly, a privileged process reached in and corrupted the state or
that the platform is broken in some way. In such a case, a task with
error state cannot be recovered from as the recovery code itself may be
incorrect or state relied upon to recover the task may be corrupted.
Moreover, if some task state is erroneous, other state in the task may
be corrupted and probably should not be saved or at least not overwrite
already saved data.
</li>
<li> Do not use undefined behaviour
C compiler's are free to do anything they want with undefined behaviour
and so the prescence of undefined behaaviour in a program makes
reasoning about the program impossible.
</li>
<li> User interaction should log errors and notify the user on failure.
If users are not notified that the action they have requested has failed
they might not notice that the code is not behaving correctly.
For example, in a well-known series of failures the Therac-21 machine
overdosed patients on too much radiation. In some of the cases, the
Therac-21 machine noticed there was a fault but reported a confusing
error message and the operators simply retried the machine resulting in
yet more overdose of radiation. In summary, at least for some software,
not reporting error messages can kill people.
</li>
</ul>
@section quality Code Quality
<ul>
<li> Do not communicate code to be executed between actors
When code to be executed is communicated between different actors a
malicious actor can often submit program code that takes over the actor
that executes the malicious actor's code.
For example, Python's pickled objects data format embeds code to be
executed inside of it and so an attacker that can submit arbitrary
pickled object data to your service to be decoded can subvert and
control it.
</li>
<li> Do not communicate credentials or privileges between actors
When credentials or privileges are communicated between actors it is
often possible for an attacker to forge fake credentials that
impersonate someone else and that gives the attacker privileges they
should not have.
For example, many insecure web electronic store fronts implement user
sessions by storing customer account information in web browser cookies.
However, a customer's session cookies are under their full control and a
malicious actor could rewrite their session cookies to indicate another
customer's user account unless said cookies are securely communicated
and private to one user's account at a time, authenticated as approved
by the web store front, and expire at a data that is in a reasonably
short time in the future.
</li>
<li> Use a clear and consistent coding style.
For example, the Linted project has it's own internal coding style which
should always be used.
</li>
<li> Accept and produce strings annotated with lengths.
Alternative encodings of strings such as null terminated strings are
difficult to reason about, often have poor algorithmic complexity and
are never very generic.
</li>
<li> Directly return error values.
For example, we often return values of type `linted_error` instead of
passing values through the thread local `errno` variable.
</li>
<li> Abort on errorneous code or corrupted program state using the
`assert` or `LINTED_IMPOSSIBILITY` macros.
This keeps the code consistent and clear in it's meaning.
</li>
<li> Abort on error cases the developer is to lazily handle at the
moment with the `LINTED_LAZY_DEV` macro.
This macro should never appear in release versions of the code.
</li>
<li> Lose capabilities by default.
Making noninheritance of capabilities the default makes it easy for one
to "not leak capabilities to new actors".
For example, nearly all files should be opened with the `O_CLOEXEC`
flag.
Another example, is that for data flags that set the actions allowable
on an object the value of zero should give as little privileges as
possible. This is no arbitrary example. A memory overwrite
vulnerability that allowed one to zero arbitrary data was usable as a
way to bypass exploit mitigations by setting the permissions of a COM
object to allow one to execute unsafe actions. Learn more at
http://www.contextis.com/blog/windows-mitigaton-bypass/.
</li>
<li> Run asynchronously or nonblockingly by default.
Runningly asynchronous or nonblockingly by default makes makes it easy
to not "needlessly waste resources" by blocking threads.
An example application of this rule is that nearly all files should be
opened with the `O_NONBLOCK` flag.
</li>
<li> Obey Linted code formatting guidelines.
Using one coding style makes it easy to "Use a clear and consistent
coding style."
Use the Linux kernel coding style but with tabs and spaces. If you are
unsure of how to format some code let the clang-format tool do it for
you.
Use `%%i` instead of `%%d` in format string specifiers.
</li>
</ul>
@section resources Other Resources
<ul>
<li> [The CERT C Coding
Standards](https://www.securecoding.cert.org/confluence/display/seccode/CERT+C+Coding+Standard)
</li>
<li> [EC-- Rule Set](http://www.leshatton.org/ISOC_subset1103.html)
</li>
<li> [Defensive
Coding](https://docs.fedoraproject.org/en-US/Fedora_Security_Team/1/html/Defensive_Coding)
</li>
<li> [Cryptography Coding
Standard](https://cryptocoding.net/index.php/Coding_rules)
Note that this standard currently has dangerous and incorrect
advice on how to use the volatile qualifier to guarantee that
memory is zeroed. In general, the compiler and the hardware are
free at any time to make hidden copies of your data (for example,
other cores on the CPU are free to cache stale copies of the data
from before it was zeroed by your cunning `memset_s` implementation
and also the CPU is free to cache the zeroing writes of the data in
a store buffer before actually clearing the data in RAM or other
core caches).
This standard also has dangerous and incorrect advice on how to
guarantee constant time behaviour for algorithms. In general, one
can not guarantee constant time behaviour without special compiler
and hardware support.
</li>
<li> [OWASP Secure Coding
Principles](https://www.owasp.org/index.php/Secure_Coding_Principles)
</li>
<li> [NISTR 8151 Dramatically Reducing Software
Vulnerabilities](http://nvlpubs.nist.gov/nistpubs/ir/2016/NIST.IR.8151.pdf)
<li> [JPL Institutional Coding Standard for the C Programming
Language](http://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdf)
</li>
</ul>
*/
|
mstewartgallus/linted | src/channel/channel.c | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#include "lntd/channel.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/sched.h"
#include "lntd/trigger.h"
#include "lntd/util.h"
#include <stdatomic.h>
#include <stdint.h>
typedef _Atomic(void *) atomic_voidptr;
struct lntd_channel {
atomic_voidptr value;
struct lntd_trigger filled;
};
lntd_error lntd_channel_create(struct lntd_channel **channelp)
{
lntd_error err;
struct lntd_channel *channel;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *channel);
if (err != 0)
return err;
channel = xx;
}
atomic_voidptr ptr = ATOMIC_VAR_INIT((void *)0);
channel->value = ptr;
lntd_trigger_create(&channel->filled, 0);
*channelp = channel;
return 0;
}
void lntd_channel_destroy(struct lntd_channel *channel)
{
lntd_trigger_destroy(&channel->filled);
lntd_mem_free(channel);
}
lntd_error lntd_channel_try_send(struct lntd_channel *channel,
void *node)
{
LNTD_ASSERT_NOT_NULL(channel);
LNTD_ASSERT_NOT_NULL(node);
void *expected = 0;
atomic_thread_fence(memory_order_release);
if (!atomic_compare_exchange_strong_explicit(
&channel->value, &expected, node, memory_order_relaxed,
memory_order_relaxed))
return LNTD_ERROR_AGAIN;
lntd_trigger_set(&channel->filled);
return 0;
}
/* Remove from the head */
void lntd_channel_recv(struct lntd_channel *channel, void **nodep)
{
LNTD_ASSERT_NOT_NULL(channel);
LNTD_ASSERT_NOT_NULL(nodep);
void *node;
for (;;) {
for (uint_fast8_t ii = 0U; ii < 20U; ++ii) {
node = atomic_exchange_explicit(
&channel->value, 0, memory_order_relaxed);
if (node != 0)
goto exit_loop;
lntd_sched_light_yield();
}
lntd_trigger_wait(&channel->filled);
}
exit_loop:
atomic_thread_fence(memory_order_acquire);
*nodep = node;
}
|
mstewartgallus/linted | src/env/env-posix.c | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/str.h"
#include "lntd/util.h"
#include <errno.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
static pthread_mutex_t mutex;
lntd_error lntd_env_set(char const *key, char const *value,
unsigned char overwrite)
{
lntd_error err = 0;
err = pthread_mutex_lock(&mutex);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
if (-1 == setenv(key, value, overwrite)) {
err = errno;
LNTD_ASSUME(err != 0);
}
{
lntd_error unlock_err = pthread_mutex_unlock(&mutex);
if (unlock_err != 0) {
LNTD_ASSERT(unlock_err != EPERM);
LNTD_ASSERT(false);
}
}
return err;
}
lntd_error lntd_env_get(char const *key, char **valuep)
{
lntd_error err = 0;
err = pthread_mutex_lock(&mutex);
if (err != 0) {
LNTD_ASSERT(err != EDEADLK);
LNTD_ASSERT(false);
}
char *value_dup = 0;
char const *value = getenv(key);
if (0 == value)
goto unlock_mutex;
{
char *xx;
err = lntd_str_dup(&xx, value);
if (err != 0)
goto unlock_mutex;
value_dup = xx;
}
unlock_mutex : {
lntd_error unlock_err = pthread_mutex_unlock(&mutex);
if (unlock_err != 0) {
LNTD_ASSERT(unlock_err != EPERM);
LNTD_ASSERT(false);
}
}
if (0 == err) {
*valuep = value_dup;
}
return err;
}
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
mstewartgallus/linted | include/lntd/trigger.h | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_TRIGGER_H
#define LNTD_TRIGGER_H
#include "lntd/error.h"
#include <stdatomic.h>
#define LNTD_TRIGGER_PSHARED 1U
struct lntd_trigger {
atomic_int _triggered;
char __padding[64U - sizeof(atomic_int) % 64U];
_Bool _process_local : 1U;
};
lntd_error lntd_trigger_create(struct lntd_trigger *trigger,
unsigned long flags);
void lntd_trigger_destroy(struct lntd_trigger *trigger);
void lntd_trigger_set(struct lntd_trigger *trigger);
void lntd_trigger_wait(struct lntd_trigger *trigger);
#endif /* LNTD_TRIGGER_H */
|
mstewartgallus/linted | src/admin/admin.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "admin.h"
#include "lntd/admin.h"
#include "lntd/async.h"
#include "lntd/error.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <rpc/xdr.h>
#include <stddef.h>
#include <string.h>
LNTD_STATIC_ASSERT(sizeof(struct lntd_admin_request) ==
sizeof(struct lntd_admin_proto_request));
LNTD_STATIC_ASSERT(sizeof(struct lntd_admin_reply) ==
sizeof(struct lntd_admin_proto_reply));
#define CHUNK_SIZE 4096U
#define ALIGN(X) \
(sizeof(struct { \
char _a; \
X _b; \
}) - \
sizeof(X))
struct lntd_admin_in_task_recv {
struct lntd_io_task_read *parent;
void *data;
char request[CHUNK_SIZE];
};
struct lntd_admin_out_task_send {
struct lntd_io_task_write *data;
void *parent;
char reply[CHUNK_SIZE];
};
lntd_error
lntd_admin_in_task_recv_create(struct lntd_admin_in_task_recv **taskp,
void *data)
{
lntd_error err;
struct lntd_admin_in_task_recv *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_io_task_read *parent;
{
struct lntd_io_task_read *xx;
err = lntd_io_task_read_create(&xx, task);
if (err != 0)
goto free_task;
parent = xx;
}
task->parent = parent;
task->data = data;
memset(task->request, 0, CHUNK_SIZE);
*taskp = task;
return 0;
free_task:
lntd_mem_free(task);
return err;
}
void lntd_admin_in_task_recv_destroy(
struct lntd_admin_in_task_recv *task)
{
lntd_io_task_read_destroy(task->parent);
lntd_mem_free(task);
}
void *lntd_admin_in_task_recv_data(struct lntd_admin_in_task_recv *task)
{
return task->data;
}
lntd_error
lntd_admin_in_task_recv_request(struct lntd_admin_request **outp,
struct lntd_admin_in_task_recv *task)
{
lntd_error err = 0;
struct lntd_admin_request *request;
{
void *xx;
err = lntd_mem_alloc_zeroed(&xx, sizeof *request);
if (err != 0)
return err;
request = xx;
}
char *raw = task->request;
XDR xdr = {0};
xdrmem_create(&xdr, raw, CHUNK_SIZE, XDR_DECODE);
if (!xdr_lntd_admin_proto_request(&xdr, (void *)request))
LNTD_ASSERT(0);
xdr_destroy(&xdr);
*outp = request;
return 0;
}
void lntd_admin_request_free(struct lntd_admin_request *request)
{
xdr_free((xdrproc_t)xdr_lntd_admin_proto_request,
(char *)request);
lntd_mem_free(request);
}
lntd_error lntd_admin_in_send(lntd_admin_in admin,
struct lntd_admin_request const *request)
{
lntd_error err = 0;
char *raw;
{
void *xx;
err = lntd_mem_alloc_zeroed(&xx, CHUNK_SIZE);
if (err != 0)
return err;
raw = xx;
}
XDR xdr = {0};
xdrmem_create(&xdr, raw, CHUNK_SIZE, XDR_ENCODE);
if (!xdr_lntd_admin_proto_request(&xdr, (void *)request))
LNTD_ASSERT(0);
err = lntd_io_write_all(admin, 0, raw, CHUNK_SIZE);
xdr_destroy(&xdr);
lntd_mem_free(raw);
return err;
}
void lntd_admin_in_task_recv_cancel(
struct lntd_admin_in_task_recv *task)
{
lntd_io_task_read_cancel(task->parent);
}
void lntd_admin_in_task_recv_submit(
struct lntd_async_pool *pool, struct lntd_admin_in_task_recv *task,
union lntd_async_ck task_ck, void *userstate, lntd_ko ko)
{
lntd_io_task_read_submit(pool, task->parent, task_ck, userstate,
ko, task->request,
sizeof task->request);
}
lntd_error
lntd_admin_out_task_send_create(struct lntd_admin_out_task_send **taskp,
void *data)
{
lntd_error err;
struct lntd_admin_out_task_send *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_io_task_write *parent;
{
struct lntd_io_task_write *xx;
err = lntd_io_task_write_create(&xx, task);
if (err != 0)
goto free_task;
parent = xx;
}
task->parent = parent;
task->data = data;
memset(task->reply, 0, CHUNK_SIZE);
*taskp = task;
return 0;
free_task:
lntd_mem_free(task);
return err;
}
void lntd_admin_out_task_send_destroy(
struct lntd_admin_out_task_send *task)
{
lntd_io_task_write_destroy(task->parent);
lntd_mem_free(task);
}
void *
lntd_admin_out_task_send_data(struct lntd_admin_out_task_send *task)
{
return task->data;
}
void lntd_admin_out_task_send_submit(
struct lntd_async_pool *pool, struct lntd_admin_out_task_send *task,
union lntd_async_ck task_ck, void *userstate, lntd_ko ko,
struct lntd_admin_reply const *reply)
{
char *tip = task->reply;
memset(tip, 0, CHUNK_SIZE);
XDR xdr = {0};
xdrmem_create(&xdr, tip, CHUNK_SIZE, XDR_ENCODE);
if (!xdr_lntd_admin_proto_reply(&xdr, (void *)reply))
LNTD_ASSERT(0);
xdr_destroy(&xdr);
lntd_io_task_write_submit(pool, task->parent, task_ck,
userstate, ko, task->reply,
sizeof task->reply);
}
void lntd_admin_out_task_send_cancel(
struct lntd_admin_out_task_send *task)
{
lntd_io_task_write_cancel(task->parent);
}
lntd_error lntd_admin_out_recv(lntd_admin_out admin,
struct lntd_admin_reply *reply)
{
lntd_error err = 0;
char *chunk;
{
void *xx;
err = lntd_mem_alloc_zeroed(&xx, CHUNK_SIZE);
if (err != 0)
return err;
chunk = xx;
}
size_t size;
{
size_t xx;
err = lntd_io_read_all(admin, &xx, chunk, CHUNK_SIZE);
if (err != 0)
goto free_chunk;
size = xx;
}
/* Sent malformed input */
if (size != CHUNK_SIZE) {
err = EPROTO;
goto free_chunk;
}
XDR xdr = {0};
xdrmem_create(&xdr, chunk, CHUNK_SIZE, XDR_DECODE);
if (!xdr_lntd_admin_proto_reply(&xdr, (void *)reply))
LNTD_ASSERT(0);
xdr_destroy(&xdr);
free_chunk:
lntd_mem_free(chunk);
return err;
}
|
mstewartgallus/linted | include/fake-stdatomic/stdatomic.h | <reponame>mstewartgallus/linted
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_STDATOMIC_H
#define LNTD_STDATOMIC_H
#include <stddef.h>
#include <stdint.h>
#define _Atomic(T) struct {volatile __typeof__(T) __val; }
#define ATOMIC_VAR_INIT(value) \
{ \
.__val = (value) \
}
#define atomic_init(obj, value) \
do { \
(obj)->__val = (value); \
} while (0)
enum memory_order {
memory_order_relaxed,
memory_order_consume,
memory_order_acquire,
memory_order_release,
memory_order_acq_rel,
memory_order_seq_cst
};
typedef enum memory_order memory_order;
void atomic_thread_fence(enum memory_order order);
void atomic_signal_fence(enum memory_order order);
#define atomic_is_lock_free(obj) 1
/*
* 7.17.6 Atomic integer types.
*/
typedef _Atomic(_Bool) atomic_bool;
typedef _Atomic(char) atomic_char;
typedef _Atomic(signed char) atomic_schar;
typedef _Atomic(unsigned char) atomic_uchar;
typedef _Atomic(short) atomic_short;
typedef _Atomic(unsigned short) atomic_ushort;
typedef _Atomic(int) atomic_int;
typedef _Atomic(unsigned int) atomic_uint;
typedef _Atomic(long) atomic_long;
typedef _Atomic(unsigned long) atomic_ulong;
typedef _Atomic(long long) atomic_llong;
typedef _Atomic(unsigned long long) atomic_ullong;
typedef _Atomic(wchar_t) atomic_wchar_t;
typedef _Atomic(int_least8_t) atomic_int_least8_t;
typedef _Atomic(uint_least8_t) atomic_uint_least8_t;
typedef _Atomic(int_least16_t) atomic_int_least16_t;
typedef _Atomic(uint_least16_t) atomic_uint_least16_t;
typedef _Atomic(int_least32_t) atomic_int_least32_t;
typedef _Atomic(uint_least32_t) atomic_uint_least32_t;
typedef _Atomic(int_least64_t) atomic_int_least64_t;
typedef _Atomic(uint_least64_t) atomic_uint_least64_t;
typedef _Atomic(int_fast8_t) atomic_int_fast8_t;
typedef _Atomic(uint_fast8_t) atomic_uint_fast8_t;
typedef _Atomic(int_fast16_t) atomic_int_fast16_t;
typedef _Atomic(uint_fast16_t) atomic_uint_fast16_t;
typedef _Atomic(int_fast32_t) atomic_int_fast32_t;
typedef _Atomic(uint_fast32_t) atomic_uint_fast32_t;
typedef _Atomic(int_fast64_t) atomic_int_fast64_t;
typedef _Atomic(uint_fast64_t) atomic_uint_fast64_t;
typedef _Atomic(intptr_t) atomic_intptr_t;
typedef _Atomic(uintptr_t) atomic_uintptr_t;
typedef _Atomic(size_t) atomic_size_t;
typedef _Atomic(ptrdiff_t) atomic_ptrdiff_t;
typedef _Atomic(intmax_t) atomic_intmax_t;
typedef _Atomic(uintmax_t) atomic_uintmax_t;
uintmax_t atomic_compare_exchange_strong_explicit(
void *object, void *expected, uintmax_t desired,
enum memory_order success, enum memory_order failure);
uintmax_t atomic_compare_exchange_weak_explicit(
void *object, void *expected, uintmax_t desired,
enum memory_order success, enum memory_order failure);
uintmax_t atomic_exchange_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_fetch_add_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_fetch_and_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_fetch_or_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_fetch_sub_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_fetch_xor_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_load_explicit(void *object, enum memory_order order);
void atomic_store_explicit(void *object, uintmax_t desired,
enum memory_order order);
uintmax_t atomic_compare_exchange_strong(void *object, void *expected,
uintmax_t desired);
uintmax_t atomic_compare_exchange_weak(void *object, void *expected,
uintmax_t desired);
uintmax_t atomic_exchange(void *object, uintmax_t desired);
uintmax_t atomic_fetch_add(void *object, uintmax_t desired);
uintmax_t atomic_fetch_and(void *object, uintmax_t desired);
uintmax_t atomic_fetch_or(void *object, uintmax_t desired);
uintmax_t atomic_fetch_sub(void *object, uintmax_t desired);
uintmax_t atomic_fetch_xor(void *object, uintmax_t desired);
uintmax_t atomic_load(void *object);
void atomic_store(void *object, void *desired);
typedef atomic_bool atomic_flag;
#define ATOMIC_FLAG_INIT ATOMIC_VAR_INIT(0)
void atomic_flag_clear_explicit(atomic_flag *flag,
enum memory_order order);
_Bool atomic_flag_test_and_set_explicit(atomic_flag *flag,
enum memory_order order);
void atomic_flag_clear(atomic_flag *flag);
_Bool atomic_flag_test_and_set(atomic_flag *flag);
#endif /* LNTD_STDATOMIC_H */
|
mstewartgallus/linted | src/path/path.c | <gh_stars>0
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/str.h"
#include <errno.h>
#include <libgen.h>
#include <stddef.h>
#include <string.h>
lntd_error lntd_path_package_runtime_dir(char **packagep)
{
lntd_error err = 0;
char *runtime_dir_path = 0;
{
char *xx;
err = lntd_env_get("XDG_RUNTIME_DIR", &xx);
if (err != 0)
return err;
runtime_dir_path = xx;
}
if (runtime_dir_path != 0)
goto got_runtime_dir_path;
{
char *xx;
err = lntd_env_get("TMPDIR", &xx);
if (err != 0)
return err;
runtime_dir_path = xx;
}
if (runtime_dir_path != 0)
goto got_runtime_dir_fallback;
{
char *xx;
err = lntd_env_get("TEMP", &xx);
if (err != 0)
return err;
runtime_dir_path = xx;
}
if (runtime_dir_path != 0)
goto got_runtime_dir_fallback;
{
char *xx;
err = lntd_env_get("TMP", &xx);
if (err != 0)
return err;
runtime_dir_path = xx;
}
if (runtime_dir_path != 0)
goto got_runtime_dir_fallback;
err =
lntd_str_format(packagep, "%s/%s", "/tmp", PACKAGE_TARNAME);
if (err != 0)
return err;
lntd_log(LNTD_LOG_WARNING,
"%s not set, falling back to runtime directory %s",
"XDG_RUNTIME_DIR", "/tmp");
return 0;
got_runtime_dir_fallback:
lntd_log(LNTD_LOG_WARNING,
"%s not set, falling back to runtime directory %s",
"XDG_RUNTIME_DIR", runtime_dir_path);
got_runtime_dir_path:
err = lntd_str_format(packagep, "%s/%s", runtime_dir_path,
PACKAGE_TARNAME);
lntd_mem_free(runtime_dir_path);
return err;
}
lntd_error lntd_path_package_data_home(char **packagep)
{
lntd_error err = 0;
char *data_home_path;
{
char *xx;
err = lntd_env_get("XDG_DATA_HOME", &xx);
if (err != 0)
return err;
data_home_path = xx;
}
if (0 == data_home_path)
goto fallback;
err = lntd_str_format(packagep, "%s/%s", data_home_path,
PACKAGE_TARNAME);
lntd_mem_free(data_home_path);
return err;
fallback:
;
char *home_path;
{
char *xx;
err = lntd_env_get("HOME", &xx);
if (err != 0)
return err;
home_path = xx;
}
if (0 == home_path)
return EACCES;
err = lntd_str_format(packagep, "%s/%s", home_path,
"local/share");
lntd_mem_free(home_path);
return err;
}
lntd_error lntd_path_base(char **basep, char const *str)
{
lntd_error err = 0;
char *str_dup;
{
char *xx;
err = lntd_str_dup(&xx, str);
if (err != 0)
return err;
str_dup = xx;
}
size_t base_len;
{
char const *base = basename(str_dup);
base_len = strlen(base);
/* MAY OVERLAP SO USE MEMMOVE! */
memmove(str_dup, base, base_len);
}
str_dup[base_len] = '\0';
{
void *xx;
err = lntd_mem_realloc(&xx, str_dup, base_len + 1U);
if (err != 0) {
lntd_mem_free(str_dup);
return err;
}
str_dup = xx;
}
*basep = str_dup;
return 0;
}
lntd_error lntd_path_dir(char **dirp, char const *str)
{
lntd_error err = 0;
char *str_dup;
{
char *xx;
err = lntd_str_dup(&xx, str);
if (err != 0)
return err;
str_dup = xx;
}
size_t dir_len;
{
char const *dir = dirname(str_dup);
dir_len = strlen(dir);
/* MAY OVERLAP SO USE MEMMOVE! */
memmove(str_dup, dir, dir_len);
}
str_dup[dir_len] = '\0';
{
void *xx;
err = lntd_mem_realloc(&xx, str_dup, dir_len + 1U);
if (err != 0) {
lntd_mem_free(str_dup);
return err;
}
str_dup = xx;
}
*dirp = str_dup;
return 0;
}
|
mstewartgallus/linted | src/linted-monitor/monitor-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/admin.h"
#include "lntd/async.h"
#include "lntd/dir.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/fifo.h"
#include "lntd/file.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/proc.h"
#include "lntd/ptrace.h"
#include "lntd/sched.h"
#include "lntd/signal.h"
#include "lntd/spawn.h"
#include "lntd/start.h"
#include "lntd/str.h"
#include "lntd/unit.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#if defined HAVE_POSIX_API
#include <sys/ptrace.h>
#include <sys/wait.h>
#endif
#ifndef PTRACE_EVENT_STOP
#define PTRACE_EVENT_STOP 128
#endif
enum { MANAGERPID,
LNTD_STARTUP,
LNTD_SANDBOX,
LNTD_WAITER,
};
static char const *const required_envs[] =
{[MANAGERPID] = "MANAGERPID", [LNTD_STARTUP] = "LINTED_STARTUP",
[LNTD_SANDBOX] = "LINTED_SANDBOX",
[LNTD_WAITER] = "LINTED_WAITER"};
static char const *const allowed_syscalls;
enum { SIGNAL_WAIT,
ADMIN_IN_READ,
ADMIN_OUT_WRITE,
KILL_READ,
MAX_TASKS };
struct monitor {
char const *process_name;
char const *startup;
char const *sandbox;
char const *waiter;
struct lntd_admin_in_task_recv *read_task;
struct lntd_admin_out_task_send *write_task;
struct lntd_signal_task_wait *signal_wait_task;
struct lntd_io_task_read *kill_read_task;
struct lntd_async_pool *pool;
struct lntd_unit_db *unit_db;
lntd_proc manager_pid;
lntd_ko kill_fifo;
lntd_admin_in admin_in;
lntd_admin_out admin_out;
lntd_ko cwd;
bool time_to_exit : 1U;
};
static lntd_error
monitor_init(struct monitor *monitor, lntd_ko admin_in,
lntd_ko admin_out, lntd_ko kill_fifo, lntd_ko cwd,
lntd_proc manager_pid, struct lntd_async_pool *pool,
char const *process_name, char const *startup,
char const *sandbox, char const *waiter);
static lntd_error monitor_destroy(struct monitor *monitor);
static lntd_error monitor_start(struct monitor *monitor);
static lntd_error monitor_stop(struct monitor *monitor);
static lntd_error dispatch(struct monitor *monitor,
union lntd_async_ck task_ck, void *userstate,
lntd_error err);
static lntd_error
monitor_on_signal(struct monitor *monitor,
struct lntd_signal_task_wait *signal_wait_task,
lntd_error err);
static lntd_error
monitor_on_admin_in_read(struct monitor *monitor,
struct lntd_admin_in_task_recv *read_task,
lntd_error err);
static lntd_error
monitor_on_admin_out_write(struct monitor *monitor,
struct lntd_admin_out_task_send *write_task,
lntd_error err);
static lntd_error
monitor_on_kill_read(struct monitor *monitor,
struct lntd_io_task_read *kill_read_task,
lntd_error err);
static lntd_error on_sigchld(struct monitor *monitor);
static lntd_error on_death_sig(struct monitor *monitor, int signo);
static lntd_error
on_add_unit(struct monitor *monitor,
struct lntd_admin_request_add_unit const *request,
struct lntd_admin_reply_add_unit *reply);
static lntd_error
on_add_socket(struct monitor *monitor,
struct lntd_admin_request_add_socket const *request,
struct lntd_admin_reply_add_socket *reply);
static lntd_error
on_status_request(lntd_proc manager_pid,
struct lntd_admin_request_status const *request,
struct lntd_admin_reply_status *reply);
static lntd_error
on_stop_request(lntd_proc manager_pid,
struct lntd_admin_request_stop const *request,
struct lntd_admin_reply_stop *reply);
static lntd_error on_child_stopped(char const *process_name,
lntd_proc pid);
static lntd_error on_child_trapped(struct monitor *monitor,
lntd_proc pid, int exit_status,
struct lntd_unit_db *unit_db);
static lntd_error on_child_signaled(char const *process_name,
lntd_proc pid, int exit_status);
static lntd_error on_child_about_to_clone(lntd_proc pid);
static lntd_error on_child_about_to_exit(struct monitor *monitor,
bool time_to_exit,
lntd_proc pid,
struct lntd_unit_db *unit_db);
static lntd_error
on_child_ptrace_event_stopped(char const *process_name, lntd_proc pid,
int exit_status);
static lntd_error service_activate(struct monitor *monitor,
struct lntd_unit *unit, bool check);
lntd_error socket_activate(struct lntd_unit_socket *unit);
static size_t null_list_size(char const *const *list);
static lntd_error service_children_terminate(lntd_proc pid);
static lntd_error pid_is_child_of(lntd_proc parent, lntd_proc child,
bool *isp);
static lntd_error dup_array(char const *const *strs, size_t strs_size,
char ***strsp);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-monitor"};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
char const *manager_pid_str;
char const *startup;
char const *sandbox;
char const *waiter;
{
char *envs[LNTD_ARRAY_SIZE(required_envs)];
for (size_t ii = 0U;
ii < LNTD_ARRAY_SIZE(required_envs); ++ii) {
char const *req = required_envs[ii];
char *value;
{
char *xx;
err = lntd_env_get(req, &xx);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
value = xx;
}
if (0 == value) {
lntd_log(LNTD_LOG_ERROR,
"%s is a required "
"environment variable",
req);
return EXIT_FAILURE;
}
envs[ii] = value;
}
manager_pid_str = envs[MANAGERPID];
startup = envs[LNTD_STARTUP];
sandbox = envs[LNTD_SANDBOX];
waiter = envs[LNTD_WAITER];
}
lntd_proc manager_pid;
{
lntd_proc yy;
err = lntd_proc_from_str(manager_pid_str, &yy);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_proc_from_str: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
manager_pid = yy;
}
char *package_runtime_dir_path;
{
char *xx;
err = lntd_path_package_runtime_dir(&xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_path_package_runtime_dir: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
package_runtime_dir_path = xx;
}
char *package_data_home_path;
{
char *xx;
err = lntd_path_package_data_home(&xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_path_package_data_home: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
package_data_home_path = xx;
}
char *process_runtime_dir_path;
{
char *xx;
err = lntd_str_format(&xx, "%s/%" PRIuMAX,
package_runtime_dir_path,
(uintmax_t)manager_pid);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_str_format: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
process_runtime_dir_path = xx;
}
char *process_data_home_path;
{
char *xx;
err = lntd_str_format(&xx, "%s/%" PRIuMAX,
package_data_home_path,
(uintmax_t)manager_pid);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_str_format: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
process_data_home_path = xx;
}
err = lntd_dir_create(0, LNTD_KO_CWD, package_runtime_dir_path,
0U, S_IRWXU);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_dir_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
err = lntd_dir_create(0, LNTD_KO_CWD, package_data_home_path,
0U, S_IRWXU);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_dir_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
err = lntd_dir_create(0, LNTD_KO_CWD, process_runtime_dir_path,
0U, S_IRWXU);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_dir_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
err = lntd_dir_create(0, LNTD_KO_CWD, process_data_home_path,
0U, S_IRWXU);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_dir_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
lntd_ko cwd;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, ".",
LNTD_KO_DIRECTORY);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_open: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
cwd = xx;
}
err = lntd_ko_change_directory(process_runtime_dir_path);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_change_directory: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
err = lntd_ko_symlink(process_data_home_path, "var");
if (err != 0) {
if (errno != EEXIST) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_symlink: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
lntd_admin_in admin_in;
{
lntd_admin_in xx;
err =
lntd_fifo_create(&xx, LNTD_KO_CWD, "admin-in",
LNTD_FIFO_RDWR, S_IRUSR | S_IWUSR);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_fifo_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
admin_in = xx;
}
lntd_admin_out admin_out;
{
lntd_admin_out xx;
err =
lntd_fifo_create(&xx, LNTD_KO_CWD, "admin-out",
LNTD_FIFO_RDWR, S_IRUSR | S_IWUSR);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_fifo_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
admin_out = xx;
}
lntd_fifo kill_fifo;
{
lntd_admin_out xx;
err =
lntd_fifo_create(&xx, LNTD_KO_CWD, "kill",
LNTD_FIFO_RDWR, S_IRUSR | S_IWUSR);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_fifo_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
kill_fifo = xx;
}
struct lntd_async_pool *pool;
{
struct lntd_async_pool *xx;
err = lntd_async_pool_create(&xx, MAX_TASKS);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_async_pool_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
pool = xx;
}
static struct monitor monitor = {0};
err = monitor_init(&monitor, admin_in, admin_out, kill_fifo,
cwd, manager_pid, pool, process_name,
startup, sandbox, waiter);
if (err != 0)
goto destroy_pool;
err = monitor_start(&monitor);
if (err != 0)
goto destroy_monitor;
for (;;) {
struct lntd_async_result result;
{
struct lntd_async_result xx;
lntd_async_pool_wait(pool, &xx);
result = xx;
}
err = dispatch(&monitor, result.task_ck,
result.userstate, result.err);
if (err != 0)
goto cancel_tasks;
}
cancel_tasks:
if (LNTD_ERROR_CANCELLED == err)
err = 0;
monitor_stop(&monitor);
for (;;) {
struct lntd_async_result result;
{
struct lntd_async_result xx;
if (LNTD_ERROR_AGAIN ==
lntd_async_pool_poll(pool, &xx))
break;
result = xx;
}
lntd_error dispatch_error =
dispatch(&monitor, result.task_ck, result.userstate,
result.err);
if (0 == err)
err = dispatch_error;
}
if (LNTD_ERROR_CANCELLED == err)
err = 0;
destroy_monitor:
monitor_destroy(&monitor);
destroy_pool:
;
lntd_error destroy_err = lntd_async_pool_destroy(pool);
if (0 == err)
err = destroy_err;
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "%s", lntd_error_string(err));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static lntd_error
monitor_init(struct monitor *monitor, lntd_ko admin_in,
lntd_ko admin_out, lntd_ko kill_fifo, lntd_ko cwd,
lntd_proc manager_pid, struct lntd_async_pool *pool,
char const *process_name, char const *startup,
char const *sandbox, char const *waiter)
{
lntd_error err = 0;
struct lntd_signal_task_wait *signal_wait_task;
{
struct lntd_signal_task_wait *xx;
err = lntd_signal_task_wait_create(&xx, 0);
if (err != 0)
return err;
signal_wait_task = xx;
}
struct lntd_admin_in_task_recv *admin_in_read_task;
{
struct lntd_admin_in_task_recv *xx;
err = lntd_admin_in_task_recv_create(&xx, 0);
if (err != 0)
goto destroy_signal_wait_task;
admin_in_read_task = xx;
}
struct lntd_admin_out_task_send *write_task;
{
struct lntd_admin_out_task_send *xx;
err = lntd_admin_out_task_send_create(&xx, 0);
if (err != 0)
goto destroy_admin_in_read_task;
write_task = xx;
}
struct lntd_io_task_read *kill_read_task;
{
struct lntd_io_task_read *xx;
err = lntd_io_task_read_create(&xx, 0);
if (err != 0)
goto destroy_write_task;
kill_read_task = xx;
}
struct lntd_unit_db *unit_db;
{
struct lntd_unit_db *xx;
err = lntd_unit_db_create(&xx);
if (err != 0)
goto destroy_kill_read_task;
unit_db = xx;
}
monitor->admin_in = admin_in;
monitor->admin_out = admin_out;
monitor->kill_fifo = kill_fifo;
monitor->cwd = cwd;
monitor->unit_db = unit_db;
monitor->manager_pid = manager_pid;
monitor->pool = pool;
monitor->signal_wait_task = signal_wait_task;
monitor->kill_read_task = kill_read_task;
monitor->read_task = admin_in_read_task;
monitor->write_task = write_task;
monitor->process_name = process_name;
monitor->startup = startup;
monitor->sandbox = sandbox;
monitor->waiter = waiter;
monitor->time_to_exit = false;
return 0;
destroy_kill_read_task:
lntd_io_task_read_destroy(kill_read_task);
destroy_write_task:
lntd_admin_out_task_send_destroy(write_task);
destroy_admin_in_read_task:
lntd_admin_in_task_recv_destroy(admin_in_read_task);
destroy_signal_wait_task:
lntd_signal_task_wait_destroy(signal_wait_task);
return err;
}
static lntd_error monitor_destroy(struct monitor *monitor)
{
return 0;
}
static lntd_error monitor_start(struct monitor *monitor)
{
lntd_error err = 0;
lntd_ko cwd = monitor->cwd;
char const *startup = monitor->startup;
struct lntd_async_pool *pool = monitor->pool;
struct lntd_admin_in_task_recv *admin_in_read_task =
monitor->read_task;
struct lntd_signal_task_wait *signal_wait_task =
monitor->signal_wait_task;
struct lntd_io_task_read *kill_read_task =
monitor->kill_read_task;
lntd_ko admin_in = monitor->admin_in;
lntd_ko kill_fifo = monitor->kill_fifo;
lntd_signal_listen_to_sigchld();
lntd_signal_task_wait_submit(
pool, signal_wait_task,
(union lntd_async_ck){.u64 = SIGNAL_WAIT},
signal_wait_task);
lntd_admin_in_task_recv_submit(
pool, admin_in_read_task,
(union lntd_async_ck){.u64 = ADMIN_IN_READ},
admin_in_read_task, admin_in);
static char dummy;
lntd_io_task_read_submit(
pool, kill_read_task,
(union lntd_async_ck){.u64 = KILL_READ}, kill_read_task,
kill_fifo, &dummy, sizeof dummy);
lntd_signal_listen_to_sighup();
lntd_signal_listen_to_sigint();
lntd_signal_listen_to_sigquit();
lntd_signal_listen_to_sigterm();
struct lntd_spawn_attr *attr;
{
struct lntd_spawn_attr *xx;
err = lntd_spawn_attr_init(&xx);
if (err != 0)
return err;
attr = xx;
}
lntd_spawn_attr_set_die_on_parent_death(attr);
{
char const *const arguments[] = {startup, "admin-in",
"admin-out", 0};
err =
lntd_spawn(0, cwd, startup, 0, attr, arguments, 0);
if (err != 0)
return err;
}
lntd_spawn_attr_destroy(attr);
return 0;
}
static lntd_error monitor_stop(struct monitor *monitor)
{
struct lntd_admin_in_task_recv *read_task = monitor->read_task;
struct lntd_admin_out_task_send *write_task =
monitor->write_task;
struct lntd_signal_task_wait *signal_wait_task =
monitor->signal_wait_task;
struct lntd_io_task_read *kill_task_read =
monitor->kill_read_task;
lntd_admin_in_task_recv_cancel(read_task);
lntd_admin_out_task_send_cancel(write_task);
lntd_signal_task_wait_cancel(signal_wait_task);
lntd_io_task_read_cancel(kill_task_read);
return 0;
}
static lntd_error dispatch(struct monitor *monitor,
union lntd_async_ck task_ck, void *userstate,
lntd_error err)
{
switch (task_ck.u64) {
case SIGNAL_WAIT:
return monitor_on_signal(monitor, userstate, err);
case ADMIN_IN_READ:
return monitor_on_admin_in_read(monitor, userstate,
err);
case ADMIN_OUT_WRITE:
return monitor_on_admin_out_write(monitor, userstate,
err);
case KILL_READ:
return monitor_on_kill_read(monitor, userstate, err);
default:
LNTD_ASSUME_UNREACHABLE();
}
}
static lntd_error
monitor_on_signal(struct monitor *monitor,
struct lntd_signal_task_wait *signal_wait_task,
lntd_error err)
{
struct lntd_async_pool *pool = monitor->pool;
if (LNTD_ERROR_CANCELLED == err)
return 0;
if (err != 0)
return err;
int signo = lntd_signal_task_wait_signo(signal_wait_task);
lntd_signal_task_wait_submit(
pool, signal_wait_task,
(union lntd_async_ck){.u64 = SIGNAL_WAIT},
signal_wait_task);
switch (signo) {
case SIGCHLD:
err = on_sigchld(monitor);
if (err != 0)
return err;
break;
case SIGHUP:
case SIGQUIT:
case SIGINT:
case SIGTERM:
err = on_death_sig(monitor, signo);
if (err != 0)
return err;
break;
}
return 0;
}
static lntd_error monitor_on_admin_in_read(
struct monitor *monitor,
struct lntd_admin_in_task_recv *admin_in_read_task, lntd_error err)
{
struct lntd_async_pool *pool = monitor->pool;
struct lntd_admin_out_task_send *write_task =
monitor->write_task;
lntd_proc manager_pid = monitor->manager_pid;
lntd_ko admin_out = monitor->admin_out;
/* Assume the other end did something bad and don't exit with
* an error. */
if (err != 0)
return 0;
struct lntd_admin_request *request;
{
struct lntd_admin_request *xx;
err = lntd_admin_in_task_recv_request(
&xx, admin_in_read_task);
if (err != 0)
return err;
request = xx;
}
lntd_admin_type type = request->type;
struct lntd_admin_reply reply;
reply.type = type;
switch (type) {
case LNTD_ADMIN_ADD_UNIT: {
struct lntd_admin_reply_add_unit yy = {0};
err = on_add_unit(
monitor, &request->lntd_admin_request_u.add_unit,
&yy);
reply.lntd_admin_reply_u.add_unit = yy;
break;
}
case LNTD_ADMIN_ADD_SOCKET: {
struct lntd_admin_reply_add_socket yy = {0};
err = on_add_socket(
monitor, &request->lntd_admin_request_u.add_socket,
&yy);
reply.lntd_admin_reply_u.add_socket = yy;
break;
}
case LNTD_ADMIN_STATUS: {
struct lntd_admin_reply_status yy = {0};
err = on_status_request(
manager_pid, &request->lntd_admin_request_u.status,
&yy);
reply.lntd_admin_reply_u.status = yy;
break;
}
case LNTD_ADMIN_STOP: {
struct lntd_admin_reply_stop yy = {0};
err = on_stop_request(
manager_pid, &request->lntd_admin_request_u.stop,
&yy);
reply.lntd_admin_reply_u.stop = yy;
break;
}
default:
LNTD_ASSUME_UNREACHABLE();
}
lntd_admin_request_free(request);
{
struct lntd_admin_reply xx = reply;
lntd_admin_out_task_send_submit(
pool, write_task,
(union lntd_async_ck){.u64 = ADMIN_OUT_WRITE},
write_task, admin_out, &xx);
}
return err;
}
static lntd_error
monitor_on_admin_out_write(struct monitor *monitor,
struct lntd_admin_out_task_send *write_task,
lntd_error err)
{
struct lntd_async_pool *pool = monitor->pool;
struct lntd_admin_in_task_recv *read_task = monitor->read_task;
lntd_admin_in admin_in = monitor->admin_in;
if (err != 0)
return 0;
lntd_admin_in_task_recv_submit(
pool, read_task,
(union lntd_async_ck){.u64 = ADMIN_IN_READ}, read_task,
admin_in);
return 0;
}
static lntd_error
monitor_on_kill_read(struct monitor *monitor,
struct lntd_io_task_read *kill_read_task,
lntd_error err)
{
struct lntd_async_pool *pool = monitor->pool;
struct lntd_unit_db *unit_db = monitor->unit_db;
lntd_proc manager_pid = monitor->manager_pid;
lntd_ko kill_fifo = monitor->kill_fifo;
if (LNTD_ERROR_CANCELLED == err)
return 0;
if (err != 0)
return err;
size_t db_size = lntd_unit_db_size(unit_db);
for (size_t ii = 0U; ii < db_size; ++ii) {
struct lntd_unit *unit =
lntd_unit_db_get_unit(unit_db, ii);
char const *name = unit->name;
lntd_unit_type type = unit->type;
if (type != LNTD_UNIT_TYPE_SERVICE)
continue;
lntd_proc pid;
{
lntd_proc xx;
lntd_error pid_err =
lntd_unit_pid(&xx, manager_pid, name);
if (ESRCH == pid_err)
continue;
if (pid_err != 0) {
if (0 == err)
err = pid_err;
continue;
}
pid = xx;
}
lntd_error kill_err = lntd_proc_kill(pid, SIGTERM);
if (kill_err != ESRCH) {
LNTD_ASSERT(kill_err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(kill_err != LNTD_ERROR_PERMISSION);
LNTD_ASSERT(0 == kill_err);
}
}
monitor->time_to_exit = true;
static char dummy;
lntd_io_task_read_submit(
pool, kill_read_task,
(union lntd_async_ck){.u64 = KILL_READ}, kill_read_task,
kill_fifo, &dummy, sizeof dummy);
return 0;
}
static lntd_error on_sigchld(struct monitor *monitor)
{
char const *process_name = monitor->process_name;
struct lntd_unit_db *unit_db = monitor->unit_db;
lntd_error err = 0;
for (;;) {
lntd_proc pid;
int exit_status;
int exit_code;
{
siginfo_t info;
info.si_pid = 0;
int wait_status =
waitid(P_ALL, -1, &info,
WEXITED | WSTOPPED | WNOHANG);
if (-1 == wait_status) {
err = errno;
LNTD_ASSUME(err != 0);
if (ECHILD == err)
return LNTD_ERROR_CANCELLED;
return err;
}
pid = info.si_pid;
if (0 == pid)
break;
exit_status = info.si_status;
exit_code = info.si_code;
}
switch (exit_code) {
case CLD_DUMPED:
case CLD_KILLED:
case CLD_EXITED:
/* Do nothing */
break;
case CLD_STOPPED:
err = on_child_stopped(process_name, pid);
break;
case CLD_TRAPPED:
err = on_child_trapped(monitor, pid,
exit_status, unit_db);
break;
default:
LNTD_ASSUME_UNREACHABLE();
}
if (err != 0)
return err;
}
return 0;
}
static lntd_error on_death_sig(struct monitor *monitor, int signo)
{
struct lntd_unit_db *unit_db = monitor->unit_db;
lntd_proc manager_pid = monitor->manager_pid;
lntd_error err = 0;
size_t db_size = lntd_unit_db_size(unit_db);
for (size_t ii = 0U; ii < db_size; ++ii) {
struct lntd_unit *unit =
lntd_unit_db_get_unit(unit_db, ii);
char const *name = unit->name;
lntd_unit_type type = unit->type;
if (type != LNTD_UNIT_TYPE_SERVICE)
continue;
lntd_proc pid;
{
lntd_proc xx;
lntd_error pid_err =
lntd_unit_pid(&xx, manager_pid, name);
if (ESRCH == pid_err)
continue;
if (pid_err != 0) {
if (0 == err)
err = pid_err;
continue;
}
pid = xx;
}
lntd_error kill_err = lntd_proc_kill(pid, signo);
if (kill_err != ESRCH) {
LNTD_ASSERT(kill_err !=
LNTD_ERROR_INVALID_PARAMETER);
LNTD_ASSERT(kill_err != LNTD_ERROR_PERMISSION);
LNTD_ASSERT(0 == err);
}
}
monitor->time_to_exit = true;
return 0;
}
static lntd_error on_child_trapped(struct monitor *monitor,
lntd_proc pid, int exit_status,
struct lntd_unit_db *unit_db)
{
bool time_to_exit = monitor->time_to_exit;
char const *process_name = monitor->process_name;
int event = exit_status >> 8U;
exit_status = exit_status & 0xFF;
switch (event) {
case 0:
return on_child_signaled(process_name, pid,
exit_status);
case PTRACE_EVENT_EXIT:
return on_child_about_to_exit(monitor, time_to_exit,
pid, unit_db);
case PTRACE_EVENT_STOP:
return on_child_ptrace_event_stopped(process_name, pid,
exit_status);
case PTRACE_EVENT_VFORK:
case PTRACE_EVENT_FORK:
case PTRACE_EVENT_CLONE:
return on_child_about_to_clone(pid);
default:
LNTD_ASSUME_UNREACHABLE();
}
}
static lntd_error on_child_stopped(char const *process_name,
lntd_proc pid)
{
lntd_error err = 0;
lntd_error seize_err = lntd_ptrace_seize(
pid, PTRACE_O_TRACECLONE | PTRACE_O_TRACEFORK |
PTRACE_O_TRACEVFORK);
if (0 == err)
err = seize_err;
lntd_error kill_err = lntd_proc_continue(pid);
if (0 == err)
err = kill_err;
return err;
}
static lntd_error on_child_signaled(char const *process_name,
lntd_proc pid, int signo)
{
lntd_error err = 0;
bool is_sigchld = SIGCHLD == signo;
int child_code;
lntd_proc child_pid;
int child_signo;
int child_status;
int child_errno;
uid_t child_uid;
clock_t child_utime;
clock_t child_stime;
{
siginfo_t info = {0};
if (is_sigchld) {
err = lntd_ptrace_getsiginfo(pid, &info);
}
lntd_error cont_err = lntd_ptrace_cont(pid, signo);
if (0 == err)
err = cont_err;
if (err != 0)
return err;
if (!is_sigchld)
return 0;
child_code = info.si_code;
child_pid = info.si_pid;
child_signo = info.si_signo;
child_status = info.si_status;
child_errno = info.si_errno;
child_uid = info.si_uid;
child_utime = info.si_utime;
child_stime = info.si_stime;
}
bool is_signal = true;
char const *code_str;
switch (child_code) {
case CLD_EXITED:
code_str = "exited";
is_signal = false;
break;
case CLD_KILLED:
code_str = "killed";
break;
case CLD_DUMPED:
code_str = "dumped";
break;
default:
code_str = "unknown";
break;
}
lntd_io_write_format(
LNTD_KO_STDERR, 0, "child exited!\n"
"\tsignal: %s\n"
"\terrno: %" PRIuMAX "\n"
"\tcode: %s\n"
"\tpid: %" PRIuMAX "\n"
"\tuid: %" PRIuMAX "\n",
lntd_signal_string(child_signo), (uintmax_t)child_errno,
code_str, (uintmax_t)child_pid, (uintmax_t)child_uid);
if (is_signal) {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"\tstatus: %s\n",
lntd_signal_string(child_status));
} else {
lntd_io_write_format(LNTD_KO_STDERR, 0,
"\tstatus: %" PRIuMAX "\n",
(uintmax_t)child_status);
}
lntd_io_write_format(
LNTD_KO_STDERR, 0, "\tutime: %" PRIuMAX "\n"
"\tstime: %" PRIuMAX "\n",
(uintmax_t)child_utime, (uintmax_t)child_stime);
return 0;
}
static lntd_error
on_child_ptrace_event_stopped(char const *process_name, lntd_proc pid,
int exit_status)
{
lntd_error err = 0;
lntd_proc self = lntd_proc_get_pid();
bool is_child;
{
bool xx;
err = pid_is_child_of(self, pid, &xx);
if (err != 0)
goto continue_process;
is_child = xx;
}
if (is_child)
goto continue_process;
{
char name[LNTD_UNIT_NAME_MAX + 1U];
err = lntd_unit_name(pid, name);
if (err != 0)
return err;
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: ptracing %" PRIi64 " %s\n",
process_name, (intmax_t)pid, name);
}
err = lntd_ptrace_setoptions(pid, PTRACE_O_TRACEEXIT);
continue_process:
;
lntd_error cont_err = lntd_ptrace_cont(pid, 0);
if (0 == err)
err = cont_err;
return err;
}
static lntd_error on_child_about_to_exit(struct monitor *monitor,
bool time_to_exit,
lntd_proc pid,
struct lntd_unit_db *unit_db)
{
lntd_error err = 0;
struct lntd_unit *unit = 0;
char const *process_name = monitor->process_name;
err = service_children_terminate(pid);
if (err != 0)
goto detach_from_process;
unsigned long status;
{
unsigned long xx;
err = lntd_ptrace_geteventmsg(pid, &xx);
if (err != 0)
goto detach_from_process;
status = xx;
}
{
char name[LNTD_UNIT_NAME_MAX + 1U];
err = lntd_unit_name(pid, name);
if (err != 0)
goto detach_from_process;
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: %s: exited with %i\n",
process_name, name,
exit_status);
} else if (WIFSIGNALED(status)) {
int signo = WTERMSIG(status);
char const *str = lntd_signal_string(signo);
if (0 == str)
str = "unknown signal";
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: %s: killed by %s\n",
process_name, name, str);
} else {
LNTD_ASSUME_UNREACHABLE();
}
unit = lntd_unit_db_get_unit_by_name(unit_db, name);
}
detach_from_process:
err = lntd_ptrace_detach(pid, 0);
if (err != 0)
return err;
if (time_to_exit)
return err;
if (0 == unit)
return err;
return err;
}
/* A sandbox creator is creating a sandbox */
static lntd_error on_child_about_to_clone(lntd_proc pid)
{
return lntd_ptrace_detach(pid, 0);
}
static lntd_error
on_add_unit(struct monitor *monitor,
struct lntd_admin_request_add_unit const *request,
struct lntd_admin_reply_add_unit *reply)
{
lntd_error err = 0;
struct lntd_unit_db *unit_db = monitor->unit_db;
char const *unit_name = request->name;
char const *unit_fstab = request->fstab;
char const *unit_chdir_path = request->chdir_path;
size_t command_size = request->command.command_len;
char **unit_command = request->command.command_val;
size_t environment_size = request->environment.environment_len;
char **unit_environment = request->environment.environment_val;
int_least64_t *timer_slack_nsec = request->timer_slack_nsec;
int_least64_t *priority = request->priority;
int_least64_t *limit_no_file = request->limit_no_file;
int_least64_t *limit_msgqueue = request->limit_msgqueue;
int_least64_t *limit_locks = request->limit_locks;
int_least64_t *limit_memlock = request->limit_memlock;
bool has_timer_slack_nsec = timer_slack_nsec != 0;
bool has_priority = priority != 0;
bool has_limit_no_file = limit_no_file != 0;
bool has_limit_msgqueue = limit_msgqueue != 0;
bool has_limit_locks = limit_locks != 0;
bool has_limit_memlock = limit_memlock != 0;
bool clone_newuser = request->clone_newuser;
bool clone_newcgroup = request->clone_newcgroup;
bool clone_newpid = request->clone_newpid;
bool clone_newipc = request->clone_newipc;
bool clone_newnet = request->clone_newnet;
bool clone_newns = request->clone_newns;
bool clone_newuts = request->clone_newuts;
bool no_new_privs = request->no_new_privs;
bool seccomp = request->seccomp;
char *name;
{
char *xx;
err = lntd_str_dup(&xx, unit_name);
if (err != 0)
return err;
name = xx;
}
char *fstab;
if (0 == strcmp("", unit_fstab)) {
fstab = 0;
} else {
char *xx;
err = lntd_str_dup(&xx, unit_fstab);
if (err != 0)
goto free_name;
fstab = xx;
}
char *chdir_path;
if (0 == strcmp("", unit_chdir_path)) {
chdir_path = 0;
} else {
char *xx;
err = lntd_str_dup(&xx, unit_chdir_path);
if (err != 0)
goto free_fstab;
chdir_path = xx;
}
char **command;
{
char **xx;
err = dup_array((char const *const *)unit_command,
command_size, &xx);
if (err != 0)
goto free_chdir_path;
command = xx;
}
char **environment;
{
char **xx;
err = dup_array((char const *const *)unit_environment,
environment_size, &xx);
if (err != 0)
goto free_command;
environment = xx;
}
struct lntd_unit *unit;
{
struct lntd_unit *xx;
err = lntd_unit_db_add_unit(unit_db, &xx);
if (err != 0)
goto free_environment;
unit = xx;
}
unit->type = LNTD_UNIT_TYPE_SERVICE;
unit->name = name;
struct lntd_unit_service *unit_service =
&unit->lntd_unit_u.service;
unit_service->command = (char const *const *)command;
unit_service->fstab = fstab;
unit_service->chdir_path = chdir_path;
unit_service->environment = (char const *const *)environment;
if (has_timer_slack_nsec)
unit_service->timer_slack_nsec = *timer_slack_nsec;
if (has_priority)
unit_service->priority = *priority;
if (has_limit_no_file)
unit_service->limit_no_file = *limit_no_file;
if (has_limit_msgqueue)
unit_service->limit_msgqueue = *limit_msgqueue;
if (has_limit_locks)
unit_service->limit_locks = *limit_locks;
if (has_limit_memlock)
unit_service->limit_memlock = *limit_memlock;
/* These aren't fully implemented yet */
unit_service->has_priority = has_priority;
unit_service->has_timer_slack_nsec = has_timer_slack_nsec;
unit_service->has_limit_no_file = has_limit_no_file;
unit_service->has_limit_locks = has_limit_locks;
unit_service->has_limit_msgqueue = has_limit_msgqueue;
unit_service->has_limit_memlock = has_limit_memlock;
unit_service->clone_newuser = clone_newuser;
unit_service->clone_newcgroup = clone_newcgroup;
unit_service->clone_newpid = clone_newpid;
unit_service->clone_newipc = clone_newipc;
unit_service->clone_newnet = clone_newnet;
unit_service->clone_newns = clone_newns;
unit_service->clone_newuts = clone_newuts;
unit_service->no_new_privs = no_new_privs;
unit_service->seccomp = seccomp;
err = service_activate(monitor, unit, false);
return err;
free_environment:
for (size_t ii = 0U; ii < environment_size; ++ii)
lntd_mem_free(environment[ii]);
lntd_mem_free(environment);
free_command:
for (size_t ii = 0U; ii < command_size; ++ii)
lntd_mem_free(command[ii]);
lntd_mem_free(command);
free_chdir_path:
lntd_mem_free(chdir_path);
free_fstab:
lntd_mem_free(fstab);
free_name:
lntd_mem_free(name);
return err;
}
static lntd_error
on_add_socket(struct monitor *monitor,
struct lntd_admin_request_add_socket const *request,
struct lntd_admin_reply_add_socket *reply)
{
lntd_error err = 0;
struct lntd_unit_db *unit_db = monitor->unit_db;
char const *unit_name = request->name;
char const *unit_path = request->path;
int32_t fifo_size = request->fifo_size;
lntd_unit_socket_type type = request->sock_type;
char *name;
{
char *xx;
err = lntd_str_dup(&xx, unit_name);
if (err != 0)
return err;
name = xx;
}
char *path;
{
char *xx;
err = lntd_str_dup(&xx, unit_path);
if (err != 0)
goto free_name;
path = xx;
}
struct lntd_unit *unit;
{
struct lntd_unit *xx;
err = lntd_unit_db_add_unit(unit_db, &xx);
if (err != 0) {
lntd_mem_free(name);
return err;
}
unit = xx;
}
unit->type = LNTD_UNIT_TYPE_SOCKET;
unit->name = name;
struct lntd_unit_socket *unit_socket =
&unit->lntd_unit_u.socket;
unit_socket->path = path;
unit_socket->fifo_size = fifo_size;
unit_socket->type = type;
err = socket_activate(unit_socket);
return err;
free_name:
lntd_mem_free(name);
return err;
}
static lntd_error
on_status_request(lntd_proc manager_pid,
struct lntd_admin_request_status const *request,
struct lntd_admin_reply_status *reply)
{
lntd_error err = 0;
bool is_up;
char const *unit_name = request->name;
err = lntd_unit_pid(0, manager_pid, unit_name);
if (err != 0) {
err = 0;
is_up = false;
goto reply;
}
/* Note that a process can be a zombie or stuck in an
* uninterruptable (unkillable as well) state even if it is
* found. Not sure if it is possible to give a useful status
* report then. */
is_up = true;
reply:
if (err != 0)
return err;
reply->is_up = is_up;
return 0;
}
static lntd_error
on_stop_request(lntd_proc manager_pid,
struct lntd_admin_request_stop const *request,
struct lntd_admin_reply_stop *reply)
{
lntd_error err = 0;
bool was_up;
char const *unit_name = request->name;
lntd_proc pid;
{
lntd_proc xx;
err = lntd_unit_pid(&xx, manager_pid, unit_name);
if (err != 0)
goto pid_find_failure;
pid = xx;
goto found_pid;
}
pid_find_failure:
err = 0;
was_up = false;
goto reply;
found_pid:
err = lntd_proc_terminate(pid);
LNTD_ASSERT(err != LNTD_ERROR_INVALID_PARAMETER);
if (err != 0) {
if (ESRCH == err)
err = 0;
was_up = false;
} else {
was_up = true;
}
reply:
if (err != 0)
return err;
reply->was_up = was_up;
return 0;
}
static lntd_error service_children_terminate(lntd_proc pid)
{
lntd_error err = 0;
lntd_proc *children;
size_t len;
{
lntd_proc *xx;
size_t yy;
err = lntd_proc_children(pid, &xx, &yy);
if (err != 0)
return err;
children = xx;
len = yy;
}
for (size_t ii = 0U; ii < len; ++ii) {
err = lntd_proc_terminate(children[ii]);
if (err != 0)
goto free_children;
}
free_children:
lntd_mem_free(children);
return err;
}
static size_t null_list_size(char const *const *list)
{
for (size_t ii = 0U;; ++ii)
if (0 == list[ii])
return ii;
}
static lntd_error pid_is_child_of(lntd_proc parent, lntd_proc child,
bool *isp)
{
lntd_error err;
lntd_proc ppid;
{
struct lntd_proc_stat xx;
err = lntd_proc_stat(child, &xx);
if (err != 0)
return err;
ppid = xx.ppid;
}
*isp = ppid == parent;
return err;
}
struct my_option {
char const *value;
bool flag : 1U;
};
enum { OPT_TRACEME,
OPT_WAITER,
OPT_CHROOTDIR,
OPT_FSTAB,
OPT_NONEWPRIVS,
OPT_LIMIT_NO_FILE,
OPT_LIMIT_MSGQUEUE,
OPT_LIMIT_LOCKS,
OPT_LIMIT_MEMLOCK,
OPT_DROPCAPS,
OPT_CHDIR,
OPT_TIMER_SLACK,
OPT_PRIORITY,
OPT_SECCOMP_FILTER,
OPT_SECCOMP_ARCH_NATIVE,
OPT_CLONE_NEWUSER,
OPT_CLONE_NEWCGROUP,
OPT_CLONE_NEWPID,
OPT_CLONE_NEWIPC,
OPT_CLONE_NEWNET,
OPT_CLONE_NEWNS,
OPT_CLONE_NEWUTS };
char const *const opt_strings[] =
{[OPT_TRACEME] = "--traceme", [OPT_WAITER] = "--waiter",
[OPT_CHROOTDIR] = "--chrootdir", [OPT_FSTAB] = "--fstab",
[OPT_NONEWPRIVS] = "--nonewprivs",
[OPT_LIMIT_NO_FILE] = "--limit-no-file",
[OPT_LIMIT_MSGQUEUE] = "--limit-msgqueue",
[OPT_LIMIT_LOCKS] = "--limit-locks",
[OPT_LIMIT_MEMLOCK] = "--limit-memlock",
[OPT_DROPCAPS] = "--dropcaps", [OPT_CHDIR] = "--chdir",
[OPT_TIMER_SLACK] = "--timer-slack", [OPT_PRIORITY] = "--priority",
[OPT_SECCOMP_FILTER] = "--seccomp-filter",
[OPT_SECCOMP_ARCH_NATIVE] = "--seccomp-arch-native",
[OPT_CLONE_NEWUSER] = "--clone-newuser",
[OPT_CLONE_NEWCGROUP] = "--clone-newcgroup",
[OPT_CLONE_NEWPID] = "--clone-newpid",
[OPT_CLONE_NEWIPC] = "--clone-newipc",
[OPT_CLONE_NEWNET] = "--clone-newnet",
[OPT_CLONE_NEWNS] = "--clone-newns",
[OPT_CLONE_NEWUTS] = "--clone-newuts"};
static lntd_error service_activate(struct monitor *monitor,
struct lntd_unit *unit, bool check)
{
lntd_error err = 0;
char const *process_name = monitor->process_name;
char const *sandbox = monitor->sandbox;
char const *waiter = monitor->waiter;
lntd_proc manager_pid = monitor->manager_pid;
lntd_ko cwd = monitor->cwd;
char const *unit_name = unit->name;
struct lntd_unit_service *unit_service =
&unit->lntd_unit_u.service;
if (!check)
goto spawn_service;
lntd_proc child;
{
lntd_proc xx;
err = lntd_unit_pid(&xx, manager_pid, unit_name);
if (err != 0)
goto service_not_found;
child = xx;
}
lntd_io_write_format(LNTD_KO_STDERR, 0,
"%s: ptracing %" PRIi64 " %s\n",
process_name, (intmax_t)child, unit_name);
return lntd_ptrace_seize(child, PTRACE_O_TRACEEXIT);
service_not_found:
if (err != ESRCH)
return err;
spawn_service:
;
char const *const *command = unit_service->command;
char const *const *environment = unit_service->environment;
bool no_new_privs = unit_service->no_new_privs;
char const *fstab = unit_service->fstab;
char const *chdir_path = unit_service->chdir_path;
bool has_timer_slack_nsec = unit_service->has_timer_slack_nsec;
bool has_priority = unit_service->has_priority;
bool has_limit_no_file = unit_service->has_limit_no_file;
bool has_limit_msgqueue = unit_service->has_limit_msgqueue;
bool has_limit_locks = unit_service->has_limit_locks;
bool has_limit_memlock = unit_service->has_limit_memlock;
bool clone_newuser = unit_service->clone_newuser;
bool clone_newcgroup = unit_service->clone_newcgroup;
bool clone_newpid = unit_service->clone_newpid;
bool clone_newipc = unit_service->clone_newipc;
bool clone_newnet = unit_service->clone_newnet;
bool clone_newns = unit_service->clone_newns;
bool clone_newuts = unit_service->clone_newuts;
bool seccomp = unit_service->seccomp;
int_least64_t timer_slack_nsec = 0;
if (has_timer_slack_nsec)
timer_slack_nsec = unit_service->timer_slack_nsec;
lntd_sched_priority priority = 0;
if (has_priority)
priority = unit_service->priority;
int_least64_t limit_no_file = 0;
if (has_limit_no_file)
limit_no_file = unit_service->limit_no_file;
int_least64_t limit_msgqueue = 0;
if (has_limit_msgqueue)
limit_msgqueue = unit_service->limit_msgqueue;
int_least64_t limit_locks = 0;
if (has_limit_locks)
limit_locks = unit_service->limit_locks;
int_least64_t limit_memlock = 0;
if (has_limit_memlock)
limit_memlock = unit_service->limit_memlock;
if (fstab != 0) {
lntd_ko name_dir;
{
lntd_ko xx;
err = lntd_dir_create(&xx, LNTD_KO_CWD,
unit_name, 0U, S_IRWXU);
if (err != 0)
return err;
name_dir = xx;
}
err =
lntd_dir_create(0, name_dir, "chroot", 0U, S_IRWXU);
lntd_ko_close(name_dir);
if (err != 0)
return err;
}
if (fstab != 0 && !clone_newns)
return LNTD_ERROR_INVALID_PARAMETER;
bool drop_caps = true;
char *limit_no_file_str = 0;
char *limit_msgqueue_str = 0;
char *limit_locks_str = 0;
char *limit_memlock_str = 0;
char *timer_slack_str = 0;
char *prio_str = 0;
char *chrootdir = 0;
char *sandbox_base = 0;
if (has_limit_no_file) {
char *xx;
err = lntd_str_format(&xx, "%" PRIi64, limit_no_file);
if (err != 0)
return err;
limit_no_file_str = xx;
}
if (has_limit_msgqueue) {
char *xx;
err = lntd_str_format(&xx, "%" PRIi64, limit_msgqueue);
if (err != 0)
goto free_strs;
limit_msgqueue_str = xx;
}
if (has_limit_locks) {
char *xx;
err = lntd_str_format(&xx, "%" PRIi64, limit_locks);
if (err != 0)
goto free_strs;
limit_locks_str = xx;
}
if (has_limit_memlock) {
char *xx;
err = lntd_str_format(&xx, "%" PRIi64, limit_memlock);
if (err != 0)
goto free_strs;
limit_memlock_str = xx;
}
if (has_timer_slack_nsec) {
char *xx;
err =
lntd_str_format(&xx, "%" PRIi64, timer_slack_nsec);
if (err != 0)
goto free_strs;
timer_slack_str = xx;
}
if (has_priority) {
char *xx;
err = lntd_str_format(&xx, "%i", priority);
if (err != 0)
goto free_strs;
prio_str = xx;
}
{
char *xx;
err = lntd_str_format(&xx, "%s/chroot", unit_name);
if (err != 0)
goto free_strs;
chrootdir = xx;
}
{
char *xx;
err = lntd_path_base(&xx, sandbox);
if (err != 0)
goto free_strs;
sandbox_base = xx;
}
size_t command_size =
null_list_size((char const *const *)command);
char const **args;
size_t num_options;
size_t args_size;
{
struct my_option const options[] =
{[OPT_TRACEME] = {0, true},
[OPT_WAITER] = {waiter, waiter != 0},
[OPT_CHROOTDIR] = {chrootdir, fstab != 0},
[OPT_FSTAB] = {fstab, fstab != 0},
[OPT_NONEWPRIVS] = {0, no_new_privs},
[OPT_LIMIT_NO_FILE] = {limit_no_file_str,
has_limit_no_file},
[OPT_LIMIT_MSGQUEUE] = {limit_msgqueue_str,
has_limit_msgqueue},
[OPT_LIMIT_LOCKS] = {limit_locks_str,
has_limit_locks},
[OPT_LIMIT_MEMLOCK] = {limit_memlock_str,
has_limit_memlock},
[OPT_DROPCAPS] = {0, drop_caps},
[OPT_CHDIR] = {chdir_path, chdir_path != 0},
[OPT_TIMER_SLACK] = {timer_slack_str,
has_timer_slack_nsec},
[OPT_PRIORITY] = {prio_str, has_priority},
[OPT_SECCOMP_FILTER] = {allowed_syscalls, seccomp},
[OPT_SECCOMP_ARCH_NATIVE] = {0, true},
[OPT_CLONE_NEWUSER] = {0, clone_newuser},
[OPT_CLONE_NEWCGROUP] = {0, clone_newcgroup},
[OPT_CLONE_NEWPID] = {0, clone_newpid},
[OPT_CLONE_NEWIPC] = {0, clone_newipc},
[OPT_CLONE_NEWNET] = {0, clone_newnet},
[OPT_CLONE_NEWNS] = {0, clone_newns},
[OPT_CLONE_NEWUTS] = {0, clone_newuts}};
num_options = 0U;
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(options);
++ii) {
struct my_option const *option = &options[ii];
char const *value = option->value;
bool flag = option->flag;
if (!flag)
continue;
++num_options;
if (value != 0)
++num_options;
}
args_size = 1U + num_options + 1U + command_size;
{
void *xx;
err = lntd_mem_alloc_array(&xx, args_size + 1U,
sizeof command[0U]);
if (err != 0)
goto free_strs;
args = xx;
}
args[0U] = sandbox_base;
size_t ix = 1U;
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(options);
++ii) {
struct my_option option = options[ii];
char const *name = opt_strings[ii];
char const *value = option.value;
bool flag = option.flag;
if (!flag)
continue;
args[ix++] = name;
if (value != 0)
args[ix++] = value;
}
}
args[1U + num_options] = "--";
for (size_t ii = 0U; ii < command_size; ++ii)
args[1U + num_options + 1U + ii] = command[ii];
args[args_size] = 0;
struct lntd_spawn_attr *attr;
{
struct lntd_spawn_attr *xx;
err = lntd_spawn_attr_init(&xx);
if (err != 0)
goto free_args;
attr = xx;
}
lntd_spawn_attr_set_die_on_parent_death(attr);
err = lntd_spawn(0, cwd, sandbox, 0, attr, args, environment);
lntd_spawn_attr_destroy(attr);
free_args:
lntd_mem_free(args);
free_strs:
lntd_mem_free(sandbox_base);
lntd_mem_free(chrootdir);
lntd_mem_free(prio_str);
lntd_mem_free(timer_slack_str);
lntd_mem_free(limit_locks_str);
lntd_mem_free(limit_msgqueue_str);
lntd_mem_free(limit_no_file_str);
return err;
}
lntd_error socket_activate(struct lntd_unit_socket *unit)
{
lntd_error err = 0;
lntd_unit_type type = unit->type;
char const *path = unit->path;
switch (type) {
case LNTD_UNIT_SOCKET_TYPE_DIR:
err =
lntd_dir_create(0, LNTD_KO_CWD, path, 0U, S_IRWXU);
break;
case LNTD_UNIT_SOCKET_TYPE_FILE:
err = lntd_file_create(0, LNTD_KO_CWD, path, 0U,
S_IRUSR | S_IWUSR);
break;
case LNTD_UNIT_SOCKET_TYPE_FIFO: {
int_least32_t fifo_size = unit->fifo_size;
#if defined F_SETPIPE_SZ
if (fifo_size >= 0) {
lntd_ko fifo;
{
lntd_ko xx;
err = lntd_fifo_create(
&xx, LNTD_KO_CWD, path,
LNTD_FIFO_RDWR, S_IRUSR | S_IWUSR);
if (err != 0)
return err;
fifo = xx;
}
if (-1 ==
fcntl(fifo, F_SETPIPE_SZ, fifo_size)) {
err = errno;
LNTD_ASSUME(err != 0);
}
lntd_error close_err = lntd_ko_close(fifo);
if (0 == err)
err = close_err;
} else
#endif
{
err = lntd_fifo_create(0, LNTD_KO_CWD, path, 0U,
S_IRUSR | S_IWUSR);
}
break;
}
}
return err;
}
static lntd_error dup_array(char const *const *strs, size_t strs_size,
char ***strsp)
{
lntd_error err = 0;
size_t new_size = strs_size + 1U;
LNTD_ASSERT(new_size > 0U);
char **new_strs;
{
void *xx;
err = lntd_mem_alloc_array(&xx, new_size,
sizeof new_strs[0U]);
if (err != 0)
return err;
new_strs = xx;
}
size_t ii = 0U;
for (; ii < strs_size; ++ii) {
err = lntd_str_dup(&new_strs[ii], strs[ii]);
if (err != 0)
goto free_new;
}
new_strs[ii] = 0;
*strsp = new_strs;
return 0;
free_new:
for (size_t jj = 0U; jj < ii; ++jj)
lntd_mem_free(new_strs[jj]);
lntd_mem_free(new_strs);
return err;
}
static char const *const allowed_syscalls =
/* Common */
"execve,"
"brk,"
"access,"
"mmap,"
"mmap2,"
"set_thread_area,"
"time,"
"gettimeofday,"
"clock_gettime,"
"clock_getres,"
"open,"
"stat,"
"stat64,"
"fstat,"
"fstat64,"
"close,"
"read,"
"mprotect,"
"arch_prctl,"
"munmap,"
"set_tid_address,"
"set_robust_list,"
"futex,"
"rt_sigaction,"
"rt_sigprocmask,"
"getrlimit,"
"ugetrlimit,"
"clone,"
"openat,"
"exit,"
"exit_group,"
"restart_syscall,"
/* Not common */
"pipe2,"
"pause,"
"lseek,"
"_llseek,"
"prctl,"
"eventfd2,"
"fcntl,"
"fcntl64,"
"epoll_create1,"
"epoll_ctl,"
"epoll_wait,"
"readlink,"
"clock_nanosleep,"
"write,"
"umask,"
"uname,"
"mkdir,"
"poll,"
"ftruncate,"
"ftruncate64,"
"writev,"
"getdents,"
"getdents64,"
"statfs,"
"pwrite64,"
"getuid,"
"getuid32,"
"geteuid,"
"geteuid32,"
"kill,"
"rt_sigtimedwait,"
"unlink,"
"getgid,"
"getgid32,"
"getegid,"
"getegid32,"
"fchown,"
"fchown32,"
"madvise,"
"ioctl,"
"pread64,"
"sched_yield,"
"fchmod,"
"lstat,"
"lstat64,"
"socketcall,"
"connect,"
"socket,"
"getpeername,"
"setsockopt,"
"getsockopt,"
"getsockname,"
"recvfrom,"
"recvmsg,"
"sendto,"
"sendmsg,"
"shutdown,"
"tgkill,"
"rt_sigreturn,"
"sigreturn,"
"ppoll,"
"timerfd_create,"
"timerfd_settime,"
"sigaltstack,"
"gettid,"
"sched_setscheduler"
#if 0
"clock_gettime,"
"dup2,"
"dup3,"
"execveat,"
"mincore,"
"wait4,"
/* Debugging related system calls */
"gettid,"
"getpid,"
"nanosleep,"
"sched_getaffinity,"
"setrlimit,"
"sigaltstack,"
/* Apitrace related system calls */
"dup,"
/* Valgrind related system calls */
"getcwd,"
"getppid,"
"gettimeofday,"
"getxattr,"
"mknod,"
"pipe,"
"pread64,"
"time,"
"tkill,"
#endif
;
|
mstewartgallus/linted | include/lntd/execveat.h | <reponame>mstewartgallus/linted
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_EXECVEAT_H
#define LNTD_EXECVEAT_H
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/util.h"
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
#if defined HAVE_POSIX_API
#include <sys/syscall.h>
#endif
static inline lntd_error lntd_execveat(lntd_ko fd, char const *binary,
char **args, char **env,
uint_least64_t opts);
#if defined HAVE_POSIX_API
#ifndef __NR_execveat
#if defined __amd64__
#define __NR_execveat 322
#elif defined __i386__
#define __NR_execveat 358
#elif defined __powerpc__
#define __NR_execveat 362
#elif defined __arm__
#define __NR_execveat (__NR_SYSCALL_BASE + 387)
#elif defined __aarch64__
/* This is the generic syscall number */
#define __NR_execveat 281
#endif
#endif
#ifdef __NR_execveat
static inline lntd_error lntd_execveat(lntd_ko fd, char const *binary,
char **args, char **env,
uint_least64_t opts)
{
syscall(__NR_execveat, (int)fd, binary, args, env, opts);
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
#endif
#endif
#endif /* LNTD_EXECVEAT_H */
|
mstewartgallus/linted | src/linted-enter/linted-enter.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/error.h"
#include "lntd/execveat.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/proc.h"
#include "lntd/start.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sched.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-enter",
.dont_init_signals = true,
0};
/* Order of entering matters */
static char const *const namespaces[] = {"user", "mnt", "pid", "ipc",
"net"};
static unsigned char lntd_start_main(char const *const process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
if (argc < 2U)
return EXIT_FAILURE;
lntd_ko sh_ko;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "/bin/sh", 0);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_open: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
sh_ko = xx;
}
lntd_proc pid = atoi(argv[1U]);
{
char proc_path[sizeof "/proc/" - 1U +
LNTD_NUMBER_TYPE_STRING_SIZE(pid_t) +
1U];
sprintf(proc_path, "/proc/%" PRIuMAX "",
(uintmax_t)pid);
err = lntd_ko_change_directory(proc_path);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_ko_change_directory: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
lntd_ko ns;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, "ns",
LNTD_KO_DIRECTORY);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_open: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
ns = xx;
}
lntd_ko fds[LNTD_ARRAY_SIZE(namespaces)];
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(namespaces); ++ii) {
lntd_ko xx;
err = lntd_ko_open(&xx, ns, namespaces[ii], 0);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_open: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
fds[ii] = xx;
}
err = lntd_ko_change_directory("root");
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_change_directory: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
/* Open all the fds at once so that one can enter spaces that
* lack /proc.
*/
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(namespaces); ++ii) {
if (-1 == setns(fds[ii], 0)) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_log(LNTD_LOG_ERROR, "setns: %s",
lntd_error_string(err));
}
}
err = lntd_ko_change_directory("/");
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_ko_change_directory: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
static const char *args[] = {"/bin/sh", 0};
err = lntd_execveat(sh_ko, "", (char **)args, environ,
AT_EMPTY_PATH);
lntd_log(LNTD_LOG_ERROR, "execve: %s", lntd_error_string(err));
return EXIT_FAILURE;
}
|
mstewartgallus/linted | src/utf/utf.c | <filename>src/utf/utf.c
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define WINVER 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/utf.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <windows.h>
lntd_error lntd_utf_2_to_1(wchar_t const *input, char **outputp)
{
lntd_error err;
size_t buffer_size = WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, input, -1, 0, 0, 0, 0);
if (0 == buffer_size) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
char *buffer;
{
void *xx;
err = lntd_mem_alloc_array(&xx, buffer_size,
sizeof buffer[0U]);
if (err != 0)
return err;
buffer = xx;
}
if (0 == WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS,
input, -1, buffer, buffer_size, 0,
0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
lntd_mem_free(buffer);
return err;
}
*outputp = buffer;
return 0;
}
lntd_error lntd_utf_1_to_2(char const *input, wchar_t **outputp)
{
lntd_error err;
size_t buffer_size = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, 0, 0);
if (0 == buffer_size) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
wchar_t *buffer;
{
void *xx;
err = lntd_mem_alloc_array(&xx, buffer_size,
sizeof buffer[0U]);
if (err != 0)
return err;
buffer = xx;
}
if (0 == MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
input, -1, buffer, buffer_size)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
lntd_mem_free(buffer);
return err;
}
*outputp = buffer;
return 0;
}
|
mstewartgallus/linted | src/signal/signal-windows.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/signal.h"
#include "lntd/async.h"
#include "lntd/fifo.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <windows.h>
/**
* @bug Either sockets or pipes need to be used
*/
enum { LNTD_SIGNAL_HUP,
LNTD_SIGNAL_INT,
LNTD_SIGNAL_TERM,
LNTD_SIGNAL_QUIT,
NUM_SIGS };
static lntd_ko sigpipe_reader = (lntd_ko)-1;
static lntd_ko sigpipe_writer = (lntd_ko)-1;
struct lntd_signal_task_wait {
struct lntd_async_task *parent;
void *data;
int signo;
};
static void write_one(lntd_ko ko);
static atomic_int sigint_signalled;
static atomic_int sigterm_signalled;
static BOOL WINAPI sigint_handler_routine(DWORD dwCtrlType);
static BOOL WINAPI sigterm_handler_routine(DWORD dwCtrlType);
lntd_error lntd_signal_init(void)
{
lntd_error err = 0;
lntd_ko reader;
lntd_ko writer;
{
lntd_ko xx;
lntd_ko yy;
err = lntd_fifo_pair(&xx, &yy, 0);
if (err != 0)
return err;
reader = xx;
writer = yy;
}
sigpipe_reader = reader;
sigpipe_writer = writer;
return 0;
}
lntd_error
lntd_signal_task_wait_create(struct lntd_signal_task_wait **taskp,
void *data)
{
lntd_error err;
struct lntd_signal_task_wait *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(
&xx, task, LNTD_ASYNCH_TASK_SIGNAL_WAIT);
if (err != 0)
goto free_task;
parent = xx;
}
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_task:
lntd_mem_free(task);
return err;
}
void lntd_signal_task_wait_destroy(struct lntd_signal_task_wait *task)
{
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void *lntd_signal_task_wait_data(struct lntd_signal_task_wait *task)
{
return task->data;
}
int lntd_signal_task_wait_signo(struct lntd_signal_task_wait *task)
{
return task->signo;
}
void lntd_signal_task_wait_submit(struct lntd_async_pool *pool,
struct lntd_signal_task_wait *task,
union lntd_async_ck task_ck,
void *userstate)
{
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
struct lntd_async_task *
lntd_signal_task_wait_to_async(struct lntd_signal_task_wait *task)
{
return task->parent;
}
struct lntd_signal_task_wait *
lntd_signal_task_wait_from_async(struct lntd_async_task *task)
{
return lntd_async_task_data(task);
}
void lntd_signal_do_wait(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_signal_task_wait *task_wait =
lntd_async_task_data(task);
lntd_error err = 0;
int signo = -1;
retry:
for (;;) {
char dummy;
DWORD xx;
if (!ReadFile(sigpipe_reader, &dummy, sizeof dummy, &xx,
0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
goto complete;
}
}
err = 0;
if (atomic_fetch_and_explicit(&sigint_signalled, 0,
memory_order_seq_cst)) {
signo = SIGINT;
goto complete;
}
if (atomic_fetch_and_explicit(&sigterm_signalled, 0,
memory_order_seq_cst)) {
signo = SIGTERM;
goto complete;
}
goto retry;
complete:
task_wait->signo = signo;
if (0 == err) {
write_one(sigpipe_writer);
}
lntd_async_pool_complete(pool, task, err);
}
char const *lntd_signal_string(int signo)
{
switch (signo) {
case SIGABRT:
return "sigabrt";
case SIGFPE:
return "sigfpe";
case SIGILL:
return "sigill";
case SIGINT:
return "sigint";
case SIGSEGV:
return "sigsegv";
case SIGTERM:
return "sigterm";
default:
return 0;
}
}
void lntd_signal_listen_to_sighup(void)
{
}
void lntd_signal_listen_to_sigint(void)
{
SetConsoleCtrlHandler(sigint_handler_routine, true);
}
void lntd_signal_listen_to_sigquit(void)
{
}
void lntd_signal_listen_to_sigterm(void)
{
SetConsoleCtrlHandler(sigterm_handler_routine, true);
}
static BOOL WINAPI sigint_handler_routine(DWORD dwCtrlType)
{
switch (dwCtrlType) {
case CTRL_C_EVENT:
atomic_store_explicit(&sigint_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
return true;
default:
return false;
}
}
static BOOL WINAPI sigterm_handler_routine(DWORD dwCtrlType)
{
switch (dwCtrlType) {
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
atomic_store_explicit(&sigterm_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
return true;
default:
return false;
}
}
static void write_one(lntd_ko ko)
{
static char const dummy;
lntd_error err = 0;
for (;;) {
size_t result;
{
DWORD xx = 0;
if (!WriteFile(ko, &dummy, 1U, &xx, 0)) {
err =
HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
}
result = xx;
}
if (0 == result)
continue;
}
LNTD_ASSERT(err !=
HRESULT_FROM_WIN32(ERROR_INVALID_USER_BUFFER));
LNTD_ASSERT(err != LNTD_ERROR_OUT_OF_MEMORY);
LNTD_ASSERT(err != HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_QUOTA));
LNTD_ASSERT(err != HRESULT_FROM_WIN32(ERROR_BROKEN_PIPE));
LNTD_ASSERT(0 == err);
}
|
mstewartgallus/linted | docs/deps.h | <gh_stars>0
/* Copyright (C) 2017 <NAME>
*
* Copying and distribution of this file, with or without
* modification, are permitted in any medium without royalty provided
* the copyright notice and this notice are preserved.
*/
/**
@file
libc6-dev
libcap-dev
libegl1-mesa-dev
libgles2-mesa-dev
libpthread-stubs0-dev
libxau-dev
libxcb1-dev
libxcb-xkb-dev
libxdmcp-dev
libxkbcommon-dev
libxkbcommon-x11-dev
gnat
libseccomp-dev
libxkbc-x11-dev
libpulse-dev
blender
nescc
libc-dev-bin
gprbuild
linux-libc-dev
x11proto-damage-dev
x11proto-kb-dev
x11proto-xf86vidmode-dev
*/
|
mstewartgallus/linted | src/io/io-windows.c | <reponame>mstewartgallus/linted
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/io.h"
#include "lntd/async.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <conio.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <windows.h>
#include <winsock2.h>
struct lntd_io_task_accept {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
lntd_ko ko;
lntd_ko returned_ko;
};
struct lntd_io_task_poll {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
lntd_ko ko;
short events;
short revents;
};
struct lntd_io_task_read {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
char *buf;
size_t size;
size_t current_position;
size_t bytes_read;
lntd_ko ko;
};
struct lntd_io_task_write {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
char const *buf;
size_t size;
size_t current_position;
size_t bytes_wrote;
lntd_ko ko;
};
struct lntd_io_task_recv {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
char *buf;
size_t size;
size_t bytes_read;
lntd_ko ko;
};
struct lntd_io_task_sendto {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
char const *buf;
size_t size;
size_t bytes_wrote;
lntd_ko ko;
struct sockaddr_storage dest_addr;
size_t dest_addr_size;
};
static lntd_error poll_one(lntd_ko ko, short events, short *revents);
static lntd_error check_for_poll_error(short revents);
lntd_error lntd_io_read_all(lntd_ko ko, size_t *bytes_read_out,
void *buf, size_t size)
{
size_t bytes_read = 0U;
size_t bytes_left = size;
lntd_error err = 0;
restart_reading:
;
size_t bytes_read_delta;
{
DWORD xx;
if (!ReadFile(ko, (char *)buf + bytes_read, bytes_left,
&xx, 0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
if (HRESULT_FROM_WIN32(ERROR_HANDLE_EOF) ==
err) {
err = 0;
goto finish_reading;
}
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto restart_reading;
if (HRESULT_FROM_WIN32(WSAEWOULDBLOCK) == err)
goto poll_for_readability;
goto finish_reading;
}
bytes_read_delta = xx;
}
bytes_read += bytes_read_delta;
bytes_left -= bytes_read_delta;
if (bytes_read_delta != 0U && bytes_left != 0U)
goto restart_reading;
finish_reading:
if (bytes_read_out != 0)
*bytes_read_out = bytes_read;
return err;
poll_for_readability:
;
short revents;
{
short xx;
err = poll_one(ko, POLLIN, &xx);
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto poll_for_readability;
if (err != 0)
goto finish_reading;
revents = xx;
}
err = check_for_poll_error(revents);
if (err != 0)
goto finish_reading;
if ((revents & POLLIN) != 0)
goto restart_reading;
if ((revents & POLLHUP) != 0)
goto finish_reading;
LNTD_ASSUME_UNREACHABLE();
}
lntd_error lntd_io_write_all(lntd_ko ko, size_t *bytes_wrote_out,
void const *buf, size_t size)
{
lntd_error err = 0;
size_t bytes_wrote = 0U;
size_t bytes_left = size;
restart_writing:
;
size_t bytes_wrote_delta;
{
DWORD xx;
if (!WriteFile(ko, (char const *)buf + bytes_wrote,
bytes_left, &xx, 0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto restart_writing;
if (HRESULT_FROM_WIN32(WSAEWOULDBLOCK) == err)
goto poll_for_writeability;
if (err != 0)
goto write_bytes_wrote;
goto write_bytes_wrote;
}
bytes_wrote_delta = xx;
}
bytes_wrote += bytes_wrote_delta;
bytes_left -= bytes_wrote_delta;
if (bytes_left != 0)
goto restart_writing;
write_bytes_wrote:
if (bytes_wrote_out != 0)
*bytes_wrote_out = bytes_wrote;
return err;
poll_for_writeability:
;
short revents;
{
short xx;
err = poll_one(ko, POLLOUT, &xx);
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto poll_for_writeability;
if (err != 0)
goto write_bytes_wrote;
revents = xx;
}
err = check_for_poll_error(revents);
if (err != 0)
goto write_bytes_wrote;
if ((revents & POLLOUT) != 0)
goto restart_writing;
LNTD_ASSUME_UNREACHABLE();
}
lntd_error lntd_io_write_string(lntd_ko ko, size_t *bytes_wrote_out,
char const *s)
{
return lntd_io_write_format(ko, bytes_wrote_out, "%s", s);
}
lntd_error lntd_io_write_format(lntd_ko ko, size_t *bytes_wrote_out,
char const *format_str, ...)
{
va_list ap;
va_start(ap, format_str);
lntd_error err =
lntd_io_write_va_list(ko, bytes_wrote_out, format_str, ap);
va_end(ap);
return err;
}
lntd_error lntd_io_write_va_list(lntd_ko ko, size_t *bytes_wrote_out,
char const *format_str, va_list list)
{
lntd_error err = 0;
int maybe_bytes = vsprintf_s(0, 0U, format_str, list);
if (maybe_bytes < 0)
return LNTD_ERROR_INVALID_PARAMETER;
size_t bytes = (size_t)maybe_bytes;
char *str;
{
void *xx;
err = lntd_mem_alloc(&xx, bytes + 1U);
if (err != 0)
return err;
str = xx;
}
str[bytes] = 0U;
if (vsprintf_s(str, bytes + 1U, format_str, list) < 0) {
err = LNTD_ERROR_INVALID_PARAMETER;
goto free_str;
}
err = lntd_io_write_all(ko, bytes_wrote_out, str, bytes);
free_str:
lntd_mem_free(str);
return err;
}
lntd_error lntd_io_task_poll_create(struct lntd_io_task_poll **taskp,
void *data)
{
lntd_error err;
struct lntd_io_task_poll *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(&xx, task,
LNTD_ASYNCH_TASK_POLL);
if (err != 0)
goto free_task;
parent = xx;
}
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
task->waiter = xx;
}
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_parent:
lntd_mem_free(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_io_task_poll_destroy(struct lntd_io_task_poll *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_io_task_poll_submit(struct lntd_async_pool *pool,
struct lntd_io_task_poll *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko ko, int flags)
{
task->ko = ko;
task->events = flags;
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
void *lntd_io_task_poll_data(struct lntd_io_task_poll *task)
{
return task->data;
}
lntd_error lntd_io_task_read_create(struct lntd_io_task_read **taskp,
void *data)
{
lntd_error err;
struct lntd_io_task_read *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(&xx, task,
LNTD_ASYNCH_TASK_READ);
if (err != 0)
goto free_task;
parent = xx;
}
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
task->waiter = xx;
}
task->parent = parent;
task->data = data;
task->current_position = 0U;
*taskp = task;
return 0;
free_parent:
lntd_mem_free(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_io_task_read_destroy(struct lntd_io_task_read *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_io_task_read_submit(struct lntd_async_pool *pool,
astruct lntd_io_task_read *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko ko, char *buf,
size_t size)
{
task->ko = ko;
task->buf = buf;
task->size = size;
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
void *lntd_io_task_read_data(struct lntd_io_task_read *task)
{
return task->data;
}
lntd_ko lntd_io_task_read_ko(struct lntd_io_task_read *task)
{
return task->ko;
}
size_t lntd_io_task_read_bytes_read(struct lntd_io_task_read *task)
{
return task->bytes_read;
}
lntd_error lntd_io_task_write_create(struct lntd_io_task_write **taskp,
void *data)
{
lntd_error err;
struct lntd_io_task_write *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(&xx, task,
LNTD_ASYNCH_TASK_WRITE);
if (err != 0)
goto free_task;
parent = xx;
}
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
task->waiter = xx;
}
task->parent = parent;
task->data = data;
task->current_position = 0U;
*taskp = task;
return 0;
free_parent:
lntd_async_task_destroy(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_io_task_write_destroy(struct lntd_io_task_write *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void lntd_io_task_write_submit(struct lntd_async_pool *pool,
struct lntd_io_task_write *task,
union lntd_async_ck task_ck,
void *userstate, lntd_ko ko,
char const *buf, size_t size)
{
task->ko = ko;
task->buf = buf;
task->size = size;
return lntd_async_task_submit(pool, task->parent, task_ck,
userstate);
}
void *lntd_io_task_write_data(struct lntd_io_task_write *task)
{
return task->data;
}
void lntd_io_do_poll(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_io_task_poll *task_poll =
lntd_async_task_data(task);
struct lntd_async_waiter *waiter = task_poll->waiter;
lntd_ko ko = task_poll->ko;
short events = task_poll->events;
short revents = lntd_async_waiter_revents(waiter);
if (0 == revents) {
lntd_async_pool_wait_on_poll(pool, waiter, task, ko,
events);
return;
}
task_poll->revents = revents;
lntd_async_pool_complete(pool, task, 0);
}
void lntd_io_do_read(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_io_task_read *task_read =
lntd_async_task_data(task);
size_t bytes_read = task_read->current_position;
size_t bytes_left = task_read->size - bytes_read;
lntd_ko ko = task_read->ko;
char *buf = task_read->buf;
struct lntd_async_waiter *waiter = task_read->waiter;
lntd_error err = 0;
size_t bytes_read_delta;
{
DWORD xx;
if (!ReadFile(ko, buf + bytes_read, bytes_left, &xx,
0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
if (HRESULT_FROM_WIN32(ERROR_HANDLE_EOF) ==
err) {
err = 0;
goto complete_task;
}
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto submit_retry;
if (HRESULT_FROM_WIN32(WSAEWOULDBLOCK) == err)
goto wait_on_poll;
goto complete_task;
}
bytes_read_delta = xx;
}
bytes_read += bytes_read_delta;
bytes_left -= bytes_read_delta;
if (bytes_read_delta != 0U && bytes_left != 0U)
goto submit_retry;
complete_task:
task_read->bytes_read = bytes_read;
task_read->current_position = 0U;
lntd_async_pool_complete(pool, task, err);
return;
submit_retry:
task_read->bytes_read = bytes_read;
task_read->current_position = bytes_read;
lntd_async_pool_resubmit(pool, task);
return;
wait_on_poll:
lntd_async_pool_wait_on_poll(pool, waiter, task, ko, POLLIN);
}
void lntd_io_do_write(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_io_task_write *task_write =
lntd_async_task_data(task);
size_t bytes_wrote = task_write->current_position;
size_t bytes_left = task_write->size - bytes_wrote;
lntd_error err = 0;
lntd_ko ko = task_write->ko;
char const *buf = task_write->buf;
size_t bytes_wrote_delta;
{
DWORD xx;
if (!WriteFile(ko, buf + bytes_wrote, bytes_left, &xx,
0)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto submit_retry;
if (HRESULT_FROM_WIN32(WSAEWOULDBLOCK) == err)
goto wait_on_poll;
if (err != 0)
goto complete_task;
goto complete_task;
}
bytes_wrote_delta = xx;
}
bytes_wrote += bytes_wrote_delta;
bytes_left -= bytes_wrote_delta;
if (bytes_left != 0U)
goto submit_retry;
complete_task:
task_write->bytes_wrote = bytes_wrote;
task_write->current_position = 0U;
lntd_async_pool_complete(pool, task, err);
return;
submit_retry:
task_write->bytes_wrote = bytes_wrote;
task_write->current_position = bytes_wrote;
lntd_async_pool_resubmit(pool, task);
return;
wait_on_poll:
lntd_async_pool_wait_on_poll(pool, task_write->waiter, task, ko,
POLLOUT);
}
static lntd_error poll_one(lntd_ko ko, short events, short *reventsp)
{
lntd_error err;
short revents;
{
struct pollfd pollfd = {.fd = (SOCKET)ko,
.events = events};
int poll_status = WSAPoll(&pollfd, 1U, -1);
if (-1 == poll_status)
goto poll_failed;
revents = pollfd.revents;
goto poll_succeeded;
}
poll_failed:
err = errno;
LNTD_ASSUME(err != 0);
return err;
poll_succeeded:
*reventsp = revents;
return 0;
}
static lntd_error check_for_poll_error(short revents)
{
lntd_error err = 0;
if ((revents & POLLNVAL) != 0)
err = LNTD_ERROR_INVALID_KO;
return err;
}
|
mstewartgallus/linted | include/lntd/util.h | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_UTIL_H
#define LNTD_UTIL_H
#include <limits.h>
#include <stddef.h>
/**
* @file
*
* Various utility macroes and functions.
*/
#if defined __GNUC__ && !defined __clang__ && !defined __CHECKER__
#define LNTD__IS_GCC 1
#else
#define LNTD__IS_GCC 0
#endif
#if defined __has_attribute
#define LNTD_UTIL_HAS_ATTRIBUTE(X) __has_attribute(X)
#else
#define LNTD_UTIL_HAS_ATTRIBUTE(X) 0
#endif
#if defined __has_builtin
#define LNTD_UTIL_HAS_BUILTIN(X) __has_builtin(X)
#else
#define LNTD_UTIL_HAS_BUILTIN(X) 0
#endif
#define LNTD_FIELD_SIZEOF(TYPE, MEMBER) (sizeof((TYPE){0}).MEMBER)
#define LNTD_ARRAY_SIZE(...) \
((sizeof __VA_ARGS__) / sizeof __VA_ARGS__[0])
#define LNTD_NUMBER_TYPE_STRING_SIZE(T) \
((CHAR_BIT * sizeof(T) - 1U) / 3U + 2U)
#if !defined __CHECKER__ && \
(LNTD_UTIL_HAS_BUILTIN(__builtin_trap) || LNTD__IS_GCC)
#define LNTD_CRASH_FAST() __builtin_trap()
#else
#define LNTD_CRASH_FAST() \
do { \
extern void abort(void); \
abort(); \
} while (0)
#endif
/**
* We need our own `LNTD_ASSERT` because the real `assert` uses
* `__FILE__`
* which is nondeterministic.
*/
#if defined NDEBUG
#define LNTD_ASSERT(...) \
do { \
} while (0)
#else
#define LNTD_ASSERT(...) \
do { \
if (!(__VA_ARGS__)) \
LNTD_CRASH_FAST(); \
} while (0)
#endif
/*
* This is needed because other uses of null can be optimized
* dangerously or because deep array accesses can index into mapped
* memory.
*/
#if defined NDEBUG
#define LNTD_ASSERT_NOT_NULL(...) \
do { \
} while (0)
#else
#define LNTD_ASSERT_NOT_NULL(...) \
do { \
if (0 == (__VA_ARGS__)) \
LNTD_CRASH_FAST(); \
} while (0)
#endif
#if defined NDEBUG
#if LNTD_UTIL_HAS_BUILTIN(__builtin_unreachable) || LNTD__IS_GCC
#define LNTD_ASSUME_UNREACHABLE() __builtin_unreachable()
#else
#define LNTD_ASSUME_UNREACHABLE() \
do { \
} while (0)
#endif
#else
#define LNTD_ASSUME_UNREACHABLE() \
do { \
LNTD_CRASH_FAST(); \
} while (0)
#endif
#if defined NDEBUG
#if LNTD_UTIL_HAS_BUILTIN(__builtin_assume)
#define LNTD_ASSUME(...) __builtin_assume((__VA_ARGS__))
#elif LNTD__IS_GCC
#define LNTD_ASSUME(...) \
do { \
if (!(__VA_ARGS__)) \
LNTD_ASSUME_UNREACHABLE(); \
} while (0)
#else
#define LNTD_ASSUME(X) \
do { \
} while (0)
#endif
#else
#define LNTD_ASSUME(X) LNTD_ASSERT(X)
#endif
#if LNTD_UTIL_HAS_ATTRIBUTE(__warn_unused_result__) || LNTD__IS_GCC
#define LNTD_WARN_UNUSED __attribute__((__warn_unused_result__))
#else
#define LNTD_WARN_UNUSED
#endif
#if LNTD_UTIL_HAS_ATTRIBUTE(__format__) || LNTD__IS_GCC
#define LNTD_FORMAT(X, Y, Z) __attribute__((__format__(X, Y, Z)))
#else
#define LNTD_FORMAT(X, Y, Z)
#endif
#if LNTD_UTIL_HAS_ATTRIBUTE(__noclone__) || LNTD__IS_GCC
#define LNTD_NOCLONE __attribute__((__noclone__))
#else
#define LNTD_NOCLONE
#endif
#if LNTD_UTIL_HAS_ATTRIBUTE(__noinline__) || LNTD__IS_GCC
#define LNTD_NOINLINE __attribute__((__noinline__))
#else
#define LNTD_NOINLINE
#endif
#if LNTD_UTIL_HAS_ATTRIBUTE(__no_sanitize_address__) || LNTD__IS_GCC
#define LNTD_NO_SANITIZE_ADDRESS \
__attribute__((__no_sanitize_address__))
#else
#define LNTD_NO_SANITIZE_ADDRESS
#endif
#define LNTD_STATIC_ASSERT_CONCAT_(A, B) A##B
#define LNTD_STATIC_ASSERT_CONCAT(A, B) LNTD_STATIC_ASSERT_CONCAT_(A, B)
#define LNTD_STATIC_ASSERT(...) \
enum { LNTD_STATIC_ASSERT_CONCAT(LNTD_ASSERT_line_, \
__LINE__) = \
1U / (!!(__VA_ARGS__)) }
#endif /* LNTD_UTIL_H */
|
mstewartgallus/linted | include/lntd/error-posix.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ERROR_H
#error this header should never be included directly
#endif
/* IWYU pragma: private, include "lntd/error.h" */
#include <errno.h>
typedef unsigned lntd_error;
#define LNTD_ERROR_AGAIN EAGAIN
#define LNTD_ERROR_CANCELLED ECANCELED
#define LNTD_ERROR_INVALID_KO EBADF
#define LNTD_ERROR_INVALID_PARAMETER EINVAL
#define LNTD_ERROR_UNIMPLEMENTED ENOSYS
#define LNTD_ERROR_OUT_OF_MEMORY ENOMEM
#define LNTD_ERROR_PERMISSION EPERM
#define LNTD_ERROR_FILE_NOT_FOUND ENOENT
|
mstewartgallus/linted | include/lntd/prctl.h | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_PRCTL_H
#define LNTD_PRCTL_H
#include "lntd/error.h"
#include "lntd/util.h"
#include <stdint.h>
#include <sys/prctl.h>
static inline lntd_error lntd_prctl_set_death_sig(int signum);
static inline lntd_error lntd_prctl_set_name(char const *name);
static inline lntd_error lntd_prctl_set_child_subreaper(_Bool v);
static inline lntd_error lntd_prctl_set_timerslack(unsigned long v);
static inline lntd_error lntd_prctl_set_no_new_privs(_Bool v);
#ifdef PR_SET_PDEATHSIG
static inline lntd_error lntd_prctl_set_death_sig(int signum)
{
lntd_error err;
if (-1 == prctl(PR_SET_PDEATHSIG, (unsigned long)signum, 0UL,
0UL, 0UL)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PR_SET_NAME
static inline lntd_error lntd_prctl_set_name(char const *name)
{
lntd_error err;
if (-1 ==
prctl(PR_SET_NAME, (unsigned long)name, 0UL, 0UL, 0UL)) {
err = errno;
LNTD_ASSUME(err != 0);
LNTD_ASSERT(err != LNTD_ERROR_INVALID_PARAMETER);
return err;
}
return 0;
}
#endif
#ifdef PR_SET_CHILD_SUBREAPER
static inline lntd_error lntd_prctl_set_child_subreaper(_Bool v)
{
lntd_error err;
if (-1 == prctl(PR_SET_CHILD_SUBREAPER, (unsigned long)v, 0UL,
0UL, 0UL)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PR_SET_TIMERSLACK
static inline lntd_error lntd_prctl_set_timerslack(unsigned long v)
{
lntd_error err;
if (-1 ==
prctl(PR_SET_TIMERSLACK, (unsigned long)v, 0UL, 0UL, 0UL)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PR_SET_NO_NEW_PRIVS
static lntd_error lntd_prctl_set_no_new_privs(_Bool b)
{
lntd_error err;
if (-1 == prctl(PR_SET_NO_NEW_PRIVS, (unsigned long)b, 0UL, 0UL,
0UL)) {
err = errno;
LNTD_ASSUME(err != 0);
LNTD_ASSERT(err != EINVAL);
return err;
}
return 0;
}
#endif
#endif /* LNTD_PRCTL_H */
|
mstewartgallus/linted | src/proc/proc-posix.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE 1
#include "config.h"
#include "lntd/proc.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#if !defined HAVE_PTHREAD_SETNAME_NP && defined HAVE_SYS_PRCTL_H
#include "lntd/prctl.h"
#endif
#include <dirent.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* 2^(bits - 1) - 1 */
/* Sadly, this assumes a twos complement implementation */
#define PID_MAX \
((pid_t)((UINTMAX_C(1) \
<< (uintmax_t)(sizeof(pid_t) * CHAR_BIT - 1U)) - \
1U))
lntd_error lntd_proc_kill(lntd_proc pid, int signo)
{
if (pid < 1)
return LNTD_ERROR_INVALID_PARAMETER;
if (signo < 1)
return LNTD_ERROR_INVALID_PARAMETER;
if (-1 == kill(pid, signo)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
lntd_error lntd_proc_terminate(lntd_proc pid)
{
return lntd_proc_kill(pid, SIGKILL);
}
lntd_error lntd_proc_continue(lntd_proc pid)
{
return lntd_proc_kill(pid, SIGCONT);
}
lntd_error lntd_proc_stat(lntd_proc pid, struct lntd_proc_stat *buf)
{
lntd_error err = 0;
lntd_ko stat_ko;
{
char path[sizeof "/proc/" - 1U +
LNTD_NUMBER_TYPE_STRING_SIZE(lntd_proc) +
sizeof "/stat" - 1U + 1U];
if (-1 == sprintf(path, "/proc/%" PRIuMAX "/stat",
(uintmax_t)pid)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, path,
LNTD_KO_RDONLY);
if (ENOENT == err)
return ESRCH;
if (err != 0)
return err;
stat_ko = xx;
}
FILE *file = fdopen(stat_ko, "r");
if (0 == file) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(stat_ko);
return err;
}
memset(buf, 0, sizeof *buf);
char *line;
ssize_t zz;
{
char *xx = 0;
size_t yy = 0U;
errno = 0;
zz = getline(&xx, &yy, file);
line = xx;
}
if (-1 == zz) {
err = errno;
/* err may be zero */
goto free_line;
}
/* If some fields are missing just leave them to be zero */
{
lntd_proc xx;
if (EOF == sscanf(line, "%" PRIuMAX " (" /* pid */
,
&xx)) {
err = errno;
LNTD_ASSUME(err != 0);
goto free_line;
}
buf->pid = xx;
}
/* Avoid troubles with processes that have names like ':-) 0 1
* 2 3 4 5'. procps-ng takes a different approach involving
* limits on the possible size of a name that I'm not actually
* sure works. */
char *start = strchr(line, '(') + 1U;
char *end = strrchr(line, ')');
memcpy(buf->comm, start, end - start);
{
lntd_proc ppid;
lntd_proc pgrp;
lntd_proc session;
lntd_proc tpgid;
if (EOF ==
sscanf(end, ")\n"
"%c\n" /* state */
"%" PRIuMAX "\n" /* ppid */
"%" PRIuMAX "\n" /* pgrp */
"%" PRIuMAX "\n" /* session */
"%d\n" /* tty_nr */
"%" PRIuMAX "\n" /* tpgid */
"%u\n" /* flags */
"%lu\n" /* minflt */
"%lu\n" /* cminflt */
"%lu\n" /* majflt */
"%lu\n" /* cmajflt */
"%lu\n" /* utime */
"%lu\n" /* stime */
"%ld\n" /* cutime */
"%ld\n" /* cstime */
"%ld\n" /* priority */
"%ld\n" /* nice */
"%ld\n" /* num_threads */
"%ld\n" /* itrealvalue */
"%llu\n" /* starttime */
"%lu\n" /* vsize */
"%ld\n" /* rss */
"%lu\n" /* rsslim */
"%lu\n" /* startcode */
"%lu\n" /* endcode */
"%lu\n" /* startstack */
"%lu\n" /* kstkesp */
"%lu\n" /* kstkeip */
"%lu\n" /* signal */
"%lu\n" /* blocked */
"%lu\n" /* sigignore */
"%lu\n" /* sigcatch */
"%lu\n" /* wchan */
"%lu\n" /* nswap */
"%lu\n" /* cnswap */
"%d\n" /* exit_signal */
"%d\n" /* processor */
"%u\n" /* rt_priority */
"%u\n" /* policy */
"%llu\n" /* delayacct_blkio_ticks */
"%lu\n" /* guest_time */
"%ld\n" /* cguest_time */
,
&buf->state, &ppid, &pgrp, &session,
&buf->tty_nr, &tpgid, &buf->flags,
&buf->minflt, &buf->cminflt, &buf->majflt,
&buf->cmajflt, &buf->utime, &buf->stime,
&buf->cutime, &buf->cstime, &buf->priority,
&buf->nice, &buf->num_threads,
&buf->itrealvalue, &buf->starttime,
&buf->vsize, &buf->rss, &buf->rsslim,
&buf->startcode, &buf->endcode,
&buf->startstack, &buf->kstkesp,
&buf->kstkeip, &buf->signal, &buf->blocked,
&buf->sigignore, &buf->sigcatch, &buf->wchan,
&buf->nswap, &buf->cnswap, &buf->exit_signal,
&buf->processor, &buf->rt_priority,
&buf->policy, &buf->delayacct_blkio_ticks,
&buf->guest_time, &buf->cguest_time)) {
err = errno;
LNTD_ASSUME(err != 0);
goto free_line;
}
buf->ppid = ppid;
buf->pgrp = pgrp;
buf->session = session;
buf->tpgid = tpgid;
}
free_line:
lntd_mem_free(line);
if (EOF == fclose(file)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return err;
}
/**
* @bug Only obtains children of the main thread.
*/
lntd_error lntd_proc_children(lntd_proc pid, lntd_proc **childrenp,
size_t *lenp)
{
lntd_error err = 0;
lntd_ko task_ko;
{
char path[sizeof "/proc/" - 1U +
LNTD_NUMBER_TYPE_STRING_SIZE(lntd_proc) +
sizeof "/task" - 1U + 1U];
if (-1 == sprintf(path, "/proc/%" PRIuMAX "/task",
(uintmax_t)pid)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, path,
LNTD_KO_RDONLY);
if (err != 0)
return err;
task_ko = xx;
}
DIR *task_dir = fdopendir(task_ko);
if (0 == task_dir) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(task_ko);
return err;
}
size_t num_tasks = 0U;
FILE **tasks = 0;
for (;;) {
errno = 0;
struct dirent *entry = readdir(task_dir);
if (0 == entry) {
err = errno;
if (err != 0)
goto close_tasks;
break;
}
char const *name = entry->d_name;
if (0 == strcmp(".", name))
continue;
if (0 == strcmp("..", name))
continue;
{
void *xx;
err = lntd_mem_realloc_array(&xx, tasks,
num_tasks + 1U,
sizeof tasks[0U]);
if (err != 0)
goto close_tasks;
tasks = xx;
}
char path[LNTD_NUMBER_TYPE_STRING_SIZE(lntd_proc) +
sizeof "/children" - 1U + 1U];
if (-1 == sprintf(path, "%s/children", name)) {
err = errno;
LNTD_ASSUME(err != 0);
goto close_tasks;
}
lntd_ko this_task;
{
lntd_ko xx;
err = lntd_ko_open(&xx, task_ko, path,
LNTD_KO_RDONLY);
if (ENOENT == err) {
err = ESRCH;
goto close_tasks;
}
if (err != 0)
goto close_tasks;
this_task = xx;
}
FILE *file = fdopen(this_task, "r");
if (0 == file) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(task_ko);
goto close_tasks;
}
tasks[num_tasks] = file;
++num_tasks;
}
size_t num_children = 0U;
lntd_proc *children = 0;
char *buf = 0;
size_t buf_size = 0U;
for (size_t ii = 0U; ii < num_tasks; ++ii) {
FILE *task = tasks[ii];
/* Get the child all at once to avoid raciness. */
bool eof = false;
ssize_t zz;
{
char *xx = buf;
size_t yy = buf_size;
errno = 0;
zz = getline(&xx, &yy, task);
buf = xx;
buf_size = yy;
}
if (-1 == zz) {
err = errno;
/* May be zero */
eof = true;
}
if (err != 0)
break;
if (eof)
continue;
char const *start = buf;
for (;;) {
errno = 0;
lntd_proc child = strtol(start, 0, 10);
err = errno;
if (err != 0)
goto free_buf;
{
void *xx;
err = lntd_mem_realloc_array(
&xx, children, num_children + 1U,
sizeof children[0U]);
if (err != 0)
goto free_buf;
children = xx;
}
children[num_children] = child;
++num_children;
start = strchr(start, ' ');
if (0 == start)
break;
if ('\n' == *start)
break;
if ('\0' == *start)
break;
++start;
if ('\n' == *start)
break;
if ('\0' == *start)
break;
}
}
free_buf:
lntd_mem_free(buf);
if (0 == err) {
*lenp = num_children;
*childrenp = children;
}
if (err != 0) {
lntd_mem_free(children);
}
close_tasks:
for (size_t ii = 0U; ii < num_tasks; ++ii) {
fclose(tasks[ii]);
}
lntd_mem_free(tasks);
closedir(task_dir);
return err;
}
lntd_proc lntd_proc_get_pid(void)
{
return getpid();
}
lntd_error lntd_proc_from_str(char const *str, lntd_proc *pidp)
{
size_t digits_count = strlen(str);
lntd_proc pid;
if ('0' == str[0U]) {
pid = 0;
goto write_pid;
}
uintmax_t maybe_pid = 0U;
uintmax_t digit_place = 1U;
for (size_t ii = digits_count; ii != 0U;) {
--ii;
char digit = str[ii];
if (digit < '0' || digit > '9')
return LNTD_ERROR_INVALID_PARAMETER;
unsigned long digit_val = digit - '0';
maybe_pid += digit_val * digit_place;
if (maybe_pid > PID_MAX)
return ERANGE;
digit_place *= 10U;
}
pid = maybe_pid;
write_pid:
*pidp = pid;
return 0;
}
#if defined HAVE_PTHREAD_SETNAME_NP
lntd_error lntd_proc_name(char const *name)
{
return pthread_setname_np(pthread_self(), name);
}
#elif defined HAVE_SYS_PRCTL_H
lntd_error lntd_proc_name(char const *name)
{
return lntd_prctl_set_name(name);
}
#else
lntd_error lntd_proc_name(char const *name)
{
return 0;
}
#endif
|
mstewartgallus/linted | src/proc/proc-windows.c | <gh_stars>0
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/proc.h"
#include "lntd/async.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <signal.h>
#include <sys/types.h>
#include <windows.h>
lntd_proc lntd_proc_get_pid(void)
{
return GetCurrentProcessId();
}
/* MSVC's way of setting thread names is really weird and hacky */
#define MS_VC_EXCEPTION 0x406D1388
#pragma pack(push, 8)
typedef struct tagTHREADNAME_INFO {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} THREADNAME_INFO;
#pragma pack(pop)
static LONG CALLBACK exception_handler(EXCEPTION_POINTERS *infop);
/**
* @todo Get Window's thread name setting to work on GCC which doesn't
* support SEH.
*/
lntd_error lntd_proc_name(char const *name)
{
THREADNAME_INFO info = {0};
/* Must be 0x1000 */
info.dwType = 0x1000;
info.szName = name;
/* Thread ID (-1=caller thread) */
info.dwThreadID = -1;
/* Reserved for the future */
info.dwFlags = 0;
void *handler =
AddVectoredExceptionHandler(1, exception_handler);
RaiseException(MS_VC_EXCEPTION, 0,
sizeof info / sizeof(ULONG_PTR),
(ULONG_PTR *)&info);
RemoveVectoredExceptionHandler(handler);
return 0;
}
static LONG CALLBACK exception_handler(EXCEPTION_POINTERS *infop)
{
return EXCEPTION_CONTINUE_EXECUTION;
}
|
mstewartgallus/linted | include/lntd/fifo.h | /*
* Copyright 2014 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_FIFO_H
#define LNTD_FIFO_H
#include "lntd/error.h"
#include "lntd/ko.h"
#include <sys/types.h>
/**
* @file
*
* Abstracts over the concept of a filesystem pipe.
*/
typedef lntd_ko lntd_fifo;
#define LNTD_FIFO_RDONLY 1UL
#define LNTD_FIFO_WRONLY (1UL << 1U)
#define LNTD_FIFO_RDWR (1UL << 2U)
#define LNTD_FIFO_ONLY (1UL << 3U)
lntd_error lntd_fifo_create(lntd_fifo *fifop, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode);
lntd_error lntd_fifo_pair(lntd_fifo *readerp, lntd_fifo *writerp,
unsigned long flags);
#endif /* LNTD_FIFO_H */
|
mstewartgallus/linted | src/file/file-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _XOPEN_SOURCE 700
#include "config.h"
#include "lntd/error.h"
#include "lntd/file.h"
#include "lntd/ko.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <sys/stat.h>
lntd_error lntd_file_create(lntd_ko *kop, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode)
{
lntd_error err;
int dirfd;
if (LNTD_KO_CWD == dirko) {
dirfd = AT_FDCWD;
} else if (dirko > INT_MAX) {
return EINVAL;
} else {
dirfd = dirko;
}
if (0 == kop) {
if (flags != 0U)
return EINVAL;
if (-1 == mknodat(dirfd, pathname, mode | S_IFREG, 0)) {
err = errno;
LNTD_ASSUME(err != 0);
if (EEXIST == err)
return 0;
return err;
}
return 0;
}
if ((flags & ~LNTD_FILE_RDONLY & ~LNTD_FILE_WRONLY &
~LNTD_FILE_RDWR & ~LNTD_FILE_SYNC & ~LNTD_FILE_EXCL) != 0U)
return EINVAL;
bool file_rdonly = (flags & LNTD_FILE_RDONLY) != 0U;
bool file_wronly = (flags & LNTD_FILE_WRONLY) != 0U;
bool file_rdwr = (flags & LNTD_FILE_RDWR) != 0U;
bool file_sync = (flags & LNTD_FILE_SYNC) != 0U;
bool file_excl = (flags & LNTD_FILE_EXCL) != 0U;
if (file_rdonly && file_wronly)
return EINVAL;
if (file_rdwr && file_rdonly)
return EINVAL;
if (file_rdwr && file_wronly)
return EINVAL;
/*
* Always, be safe for execs and use O_NONBLOCK because async
* functions handle that anyways and open may block otherwise.
*/
int oflags = O_CLOEXEC | O_NONBLOCK | O_CREAT;
/* FIFO writers give ENXIO for nonblocking opens without
* partners */
if (!file_wronly)
oflags |= O_NONBLOCK;
if (file_rdonly)
oflags |= O_RDONLY;
if (file_wronly)
oflags |= O_WRONLY;
if (file_rdwr)
oflags |= O_RDWR;
if (file_sync)
oflags |= O_SYNC;
if (file_excl)
oflags |= O_EXCL;
int fd;
do {
fd = openat(dirfd, pathname, oflags, mode);
if (-1 == fd) {
err = errno;
LNTD_ASSUME(err != 0);
} else {
err = 0;
}
} while (EINTR == err);
if (err != 0)
return err;
if (file_wronly) {
if (-1 == fcntl(fd, F_SETFL, O_NONBLOCK | oflags)) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(fd);
return err;
}
}
*kop = fd;
return 0;
}
|
mstewartgallus/linted | include/lntd/spawn.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_SPAWN_H
#define LNTD_SPAWN_H
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/proc.h"
/**
* @file
*
* Safely, spawn a new process.
*/
struct lntd_spawn_file_actions;
struct lntd_spawn_attr;
lntd_error lntd_spawn_attr_init(struct lntd_spawn_attr **attrp);
void lntd_spawn_attr_destroy(struct lntd_spawn_attr *attr);
lntd_error lntd_spawn_file_actions_init(
struct lntd_spawn_file_actions **file_actionsp);
void lntd_spawn_file_actions_destroy(
struct lntd_spawn_file_actions *file_actions);
void lntd_spawn_attr_set_die_on_parent_death(
struct lntd_spawn_attr *attrp);
void lntd_spawn_file_actions_set_stdin(
struct lntd_spawn_file_actions *file_actions, lntd_ko newko);
void lntd_spawn_file_actions_set_stdout(
struct lntd_spawn_file_actions *file_actions, lntd_ko newko);
void lntd_spawn_file_actions_set_stderr(
struct lntd_spawn_file_actions *file_actions, lntd_ko newko);
lntd_error
lntd_spawn(lntd_proc *childp, lntd_ko dirko, char const *path,
struct lntd_spawn_file_actions const *file_actions,
struct lntd_spawn_attr const *attr, char const *const argv[],
char const *const envp[]);
#endif /* LNTD_SPAWN_H */
|
mstewartgallus/linted | docs/guarding.h | /* Copyright (C) 2013,2015,2017 <NAME>
Copying and distribution of this file, with or without
modification, are permitted in any medium without royalty provided
the copyright notice and this notice are preserved.
*/
/**
@file
Linted -- Guarding
The goal of Linted is to try out techniques for making high-assurance
software and make these techniques easier to use for the common coder.
NISTR 8151 has identified five main approaches for software security:
Formal Methods, System Level Security, Additive Software Analysis
Techniques, More Mature Domain-Specific Software Development
Frameworks, Moving Target Defenses (MTD) and Automatic Software
Diversity.
@section used Used Techniques
<ul>
<li> Toolchain hardening options:
<ul>
<li> @see m4/linted_harden.m4 </li>
<li> position independent executables </li>
</ul></li>
<li> Program linters, see:
<ul>
<li> @see scripts/check-cppcheck.in </li>
<li> @see scripts/check-clang-analysis.in </li>
<li> @see scripts/check-iwyu.in </li>
</ul></li>
<li> A few unit tests (we need more) </li>
<li> Unit tests are also run under Valgrind (alternate dynamic
checkers like electric fence or duma might have advantages) </li>
</ul>
@subsection isolation Process Isolation
<ul>
<li> @see src/linted-monitor/monitor.c </li>
<li> @see src/linted-sandbox/sandbox.c </li>
<li> @see src/linted/linted.c (prevents file descriptor leaks) </li>
<li> we use sandbox specific chroots</li>
<li> we use new namespaces for sandboxes (`CLONE_NEWUSER`,
`CLONE_NEWIPC`, `CLONE_NEWNS`, `CLONE_NEWUTS`, `CLONE_NEWNET`,
`CLONE_NEWPID`) </li>
<li> we sanitize environment variables </li>
<li> we set a generic low scheduling policy for sandboxes </li>
<li> we use a generic Seccomp policy for sandboxes </li>
<li> we use generic resource limits for sandboxes </li>
</ul>
@subsection determinism Determinism
To achieve more determinism we define `__FILE__` to be the null
pointer.
We use the options: `-fno-working-directory`,
`-gno-record-gcc-switches`,
`-fdebug-prefix-map=${srcdir}=.`.
We set the environment variable `PWD` to be `/proc/self/cwd`.
We give `ranlib` the `-D` option.
We give `ar` the `D` option.
We set the `frandom-seed` option to be a hash of the source file.
@section formal-methods Formal Methods
The process of proving properties of a program using formal methods
generally consists of three parts:
- program specification
- desired property or theorem specification
- proof that the program specification satisfies the theorem.
@subsection program-specification Program Specification
Before one can prove properties of a program one must define it in a
formal and unambiguous way.
There are three common approaches to creating a formal specification
of a program:
- Automatic extraction of the program from the program specification.
- Automatic extraction of the specification from the program.
- Manual specification creation and manual verification that the
specification matches the program code.
@subsection theorem-specification Theorem Specification
Before one can prove properties of a program one must first define
those properties and the theorems one wants to prove in a formal and
unambiguous way. Too many people gloss over and forget about this
step. One should make sure that one is actually verifying the
properties that one thinks one is.
@subsection theorem-proof Theorem Proof
Finally, one must actually prove the theorems or theorem one wants to
prove.
There are four common approaches to proving program theorems:
- Automatic proof by way of abstract interpretation.
- Automatic proof by way of model checking.
- Manual proof generation and automatic checking.
- Manual proof generation and manual proof checking.
@subsection analysis Analysis
There are many, many, many tools for automatic theorem proving. There
do not seem to be any production ready tools for automatic program
specification. Manual program specification is far too fragile.
@section potential Potential Techniques
- Use fine-grained and sandbox specific scheduling policies
- Use fine-grained and sandbox specific seccomp policies
- Use fine-grained and sandbox specific resource limits
- Restrict Capabilities:
- Ftrace
- SELinux
- AppArmor
- Formal Analysis Tools:
- Frama C
- CBMC
- Model Checking:
- Our interprocess interactions might be a good area to formalize.
- Testing:
- Using much more unit tests
- Using fuzz tests
- Toolchain hardening:
- stack smashing protection with -fstack-protector-all
*/
|
mstewartgallus/linted | include/lntd/gpu.h | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_GPU_H
#define LNTD_GPU_H
#include "lntd/error.h"
#include <stdint.h>
/**
* @file
*
* Draws graphics using the GPU.
*/
typedef uint_fast32_t lntd_gpu_x11_window;
struct lntd_gpu_context;
struct lntd_gpu_update {
float z_rotation;
float x_rotation;
float x_position;
float y_position;
float z_position;
float mx_position;
float my_position;
float mz_position;
};
lntd_error
lntd_gpu_context_create(struct lntd_gpu_context **gpu_contextp);
lntd_error
lntd_gpu_context_destroy(struct lntd_gpu_context *gpu_context);
lntd_error lntd_gpu_set_x11_window(struct lntd_gpu_context *gpu_context,
lntd_gpu_x11_window x11_window);
lntd_error lntd_gpu_remove_window(struct lntd_gpu_context *gpu_context);
void lntd_gpu_update_state(struct lntd_gpu_context *gpu_context,
struct lntd_gpu_update const *gpu_update);
void lntd_gpu_resize(struct lntd_gpu_context *gpu_context,
unsigned width, unsigned height);
void lntd_gpu_hide(struct lntd_gpu_context *gpu_context);
void lntd_gpu_show(struct lntd_gpu_context *gpu_context);
#endif /* LNTD_GPU_H */
|
mstewartgallus/linted | include/lntd/ko-stack.h | <reponame>mstewartgallus/linted
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_KO_STACK_H
#define LNTD_KO_STACK_H
#include "lntd/ko.h"
struct lntd_node;
struct lntd_ko_stack;
lntd_error lntd_ko_stack_create(struct lntd_ko_stack **queuep);
void lntd_ko_stack_destroy(struct lntd_ko_stack *queue);
void lntd_ko_stack_send(struct lntd_ko_stack *queue,
struct lntd_node *node);
lntd_error lntd_ko_stack_try_recv(struct lntd_ko_stack *queue,
struct lntd_node **nodep);
lntd_ko lntd_ko_stack_ko(struct lntd_ko_stack *queue);
#endif /* LNTD_KO_STACK_H */
|
mstewartgallus/linted | src/ko/ko-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _XOPEN_SOURCE 700
#include "config.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
/* Android's libc does not have the pthread_sigmask declaration in
* signal.h as mandated by POSIX. */
#if defined __BIONIC__
#include <pthread.h>
#endif
lntd_error lntd_ko_open(lntd_ko *kop, lntd_ko dirko,
char const *pathname, unsigned long flags)
{
lntd_error err;
if (LNTD_KO_CWD == dirko) {
dirko = AT_FDCWD;
} else if (dirko > INT_MAX) {
return LNTD_ERROR_INVALID_PARAMETER;
}
unsigned long perm_flags =
LNTD_KO_RDONLY | LNTD_KO_WRONLY | LNTD_KO_RDWR;
unsigned long type_flags = LNTD_KO_DIRECTORY | LNTD_KO_FIFO;
unsigned long misc_flags = LNTD_KO_APPEND | LNTD_KO_SYNC;
unsigned long all_flags = perm_flags | type_flags | misc_flags;
if ((flags & ~all_flags) != 0U)
return LNTD_ERROR_INVALID_PARAMETER;
bool ko_rdonly = (flags & LNTD_KO_RDONLY) != 0U;
bool ko_wronly = (flags & LNTD_KO_WRONLY) != 0U;
bool ko_rdwr = (flags & LNTD_KO_RDWR) != 0U;
bool ko_append = (flags & LNTD_KO_APPEND) != 0U;
bool ko_sync = (flags & LNTD_KO_SYNC) != 0U;
bool ko_directory = (flags & LNTD_KO_DIRECTORY) != 0U;
bool ko_fifo = (flags & LNTD_KO_FIFO) != 0U;
if (ko_rdonly && ko_wronly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_rdwr && ko_rdonly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_rdwr && ko_wronly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_append && !ko_wronly)
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_directory &&
(ko_rdonly || ko_wronly || ko_rdwr || ko_append || ko_sync))
return LNTD_ERROR_INVALID_PARAMETER;
if (ko_fifo && ko_sync)
return LNTD_ERROR_INVALID_PARAMETER;
/*
* Always, be safe for execs and terminals.
*/
int oflags = O_CLOEXEC | O_NOCTTY;
/* FIFO writers give ENXIO for nonblocking opens without
* partners */
if (!ko_wronly)
oflags |= O_NONBLOCK;
if (ko_rdonly)
oflags |= O_RDONLY;
if (ko_wronly)
oflags |= O_WRONLY;
if (ko_rdwr)
oflags |= O_RDWR;
if (ko_append)
oflags |= O_APPEND;
if (ko_sync)
oflags |= O_SYNC;
if (ko_directory)
oflags |= O_DIRECTORY;
int fd;
do {
fd = openat(dirko, pathname, oflags);
if (-1 == fd) {
err = errno;
LNTD_ASSUME(err != 0);
} else {
err = 0;
}
} while (EINTR == err);
if (err != 0)
return err;
if (ko_fifo) {
mode_t mode;
{
struct stat buf;
if (-1 == fstat(fd, &buf)) {
err = errno;
LNTD_ASSUME(err != 0);
goto close_file;
}
mode = buf.st_mode;
}
if (!S_ISFIFO(mode)) {
err = LNTD_ERROR_INVALID_PARAMETER;
goto close_file;
}
}
if (ko_wronly) {
if (-1 ==
fcntl(fd, F_SETFL, (long)oflags | O_NONBLOCK)) {
err = errno;
LNTD_ASSUME(err != 0);
goto close_file;
}
}
*kop = fd;
return 0;
close_file:
lntd_ko_close(fd);
return err;
}
lntd_error lntd_ko_close(lntd_ko ko)
{
lntd_error err;
/*
* The state of a file descriptor after close gives an EINTR
* error is unspecified by POSIX so this function avoids the
* problem by simply blocking all signals.
*/
sigset_t sigset;
/* First use the signal set for the full set */
sigfillset(&sigset);
err = pthread_sigmask(SIG_BLOCK, &sigset, &sigset);
if (err != 0)
return err;
/* Then reuse the signal set for the old set */
if (-1 == close(ko)) {
err = errno;
LNTD_ASSUME(err != 0);
} else {
err = 0;
}
lntd_error mask_err = pthread_sigmask(SIG_SETMASK, &sigset, 0);
if (0 == err)
err = mask_err;
return err;
}
lntd_error lntd_ko_change_directory(char const *pathname)
{
if (-1 == chdir(pathname)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
lntd_error lntd_ko_symlink(char const *oldpath, char const *newpath)
{
if (-1 == symlink(oldpath, newpath)) {
lntd_error err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
/**
* @todo POSIX: work on directories other than `LNTD_KO_CWD`.
*/
lntd_error lntd_ko_real_path(char **resultp, lntd_ko dirko,
char const *pathname)
{
lntd_error err = 0;
LNTD_ASSERT(resultp != 0);
LNTD_ASSERT(pathname != 0);
if (dirko != LNTD_KO_CWD)
return LNTD_ERROR_INVALID_PARAMETER;
char *result = realpath(pathname, 0);
if (0 == result) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
*resultp = result;
return 0;
}
|
mstewartgallus/linted | src/ko-stack/ko-stack.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/error.h"
#include "lntd/ko-stack.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/node.h"
#include "lntd/sched.h"
#include "lntd/util.h"
#include <errno.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/eventfd.h>
#include <unistd.h>
typedef _Atomic(struct lntd_node *) atomic_node;
struct lntd_ko_stack {
int waiter_fd;
char __padding1[64U - sizeof(int)];
atomic_node inbox;
char __padding2[64U - sizeof(atomic_node)];
struct lntd_node *outbox;
};
static inline void refresh_node(struct lntd_node *node)
{
node->next = 0;
}
lntd_error lntd_ko_stack_create(struct lntd_ko_stack **stackp)
{
lntd_error err = 0;
struct lntd_ko_stack *stack;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *stack);
if (err != 0)
return err;
stack = xx;
}
atomic_node ptr = ATOMIC_VAR_INIT((void *)0);
stack->inbox = ptr;
stack->outbox = 0;
int waiter_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (-1 == waiter_fd) {
err = errno;
LNTD_ASSUME(err != 0);
goto free_stack;
}
stack->waiter_fd = waiter_fd;
*stackp = stack;
return 0;
free_stack:
lntd_mem_free(stack);
return err;
}
void lntd_ko_stack_destroy(struct lntd_ko_stack *stack)
{
lntd_ko_close(stack->waiter_fd);
lntd_mem_free(stack);
}
void lntd_ko_stack_send(struct lntd_ko_stack *stack,
struct lntd_node *node)
{
lntd_error err = 0;
lntd_ko waiter_fd = stack->waiter_fd;
for (;;) {
struct lntd_node *next = atomic_load_explicit(
&stack->inbox, memory_order_relaxed);
node->next = next;
atomic_thread_fence(memory_order_release);
if (atomic_compare_exchange_weak_explicit(
&stack->inbox, &next, node,
memory_order_relaxed, memory_order_relaxed)) {
break;
}
lntd_sched_light_yield();
}
for (;;) {
static uint64_t const xx = 0xFF;
if (-1 == write(waiter_fd, &xx, sizeof xx)) {
err = errno;
LNTD_ASSERT(err != 0);
if (EINTR == err)
continue;
LNTD_ASSERT(false);
}
break;
}
}
lntd_error lntd_ko_stack_try_recv(struct lntd_ko_stack *stack,
struct lntd_node **nodep)
{
struct lntd_node *ret = atomic_exchange_explicit(
&stack->inbox, 0, memory_order_relaxed);
if (ret != 0)
goto put_on_outbox;
ret = stack->outbox;
if (ret != 0) {
stack->outbox = ret->next;
goto give_node;
}
return EAGAIN;
put_on_outbox:
atomic_thread_fence(memory_order_acquire);
struct lntd_node *start = ret->next;
if (start != 0) {
struct lntd_node *end = start;
for (;;) {
struct lntd_node *next = end->next;
if (0 == next)
break;
end = next;
}
end->next = stack->outbox;
stack->outbox = start;
}
give_node:
refresh_node(ret);
*nodep = ret;
return 0;
}
lntd_ko lntd_ko_stack_ko(struct lntd_ko_stack *stack)
{
return stack->waiter_fd;
}
|
mstewartgallus/linted | include/lntd/async.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_ASYNCH_H
#define LNTD_ASYNCH_H
#include "lntd/error.h"
#include "lntd/ko.h"
/**
* @file
*
* Schedule tasks on kernel objects to be completed asyncronously.
*/
/* This can't be a POSIX real-time signal as those queue up so we can
* end up queuing a barrage of signals that trap the thread were
* waiting in signal handling.
*/
#define LNTD_ASYNCH_SIGNO SIGUSR1
struct lntd_async_pool;
enum { LNTD_ASYNCH_TASK_IDLE,
LNTD_ASYNCH_TASK_POLL,
LNTD_ASYNCH_TASK_READ,
LNTD_ASYNCH_TASK_WRITE,
LNTD_ASYNCH_TASK_SIGNAL_WAIT,
LNTD_ASYNCH_TASK_SLEEP_UNTIL };
typedef unsigned char lntd_async_type;
struct lntd_async_task;
struct lntd_async_waiter;
union lntd_async_ck {
void *ptr;
/* By C standards at least 8 bits long */
unsigned char u8;
/* By C standards at least 16 bits long */
unsigned short u16;
/* By C standards at least 32 bits long */
unsigned long u32;
/* By C standards at least 64 bits long */
unsigned long long u64;
};
struct lntd_async_result {
union lntd_async_ck task_ck;
void *userstate;
lntd_error err;
};
lntd_error lntd_async_pool_create(struct lntd_async_pool **poolp,
unsigned max_tasks);
lntd_error lntd_async_pool_destroy(struct lntd_async_pool *pool);
void lntd_async_pool_resubmit(struct lntd_async_pool *pool,
struct lntd_async_task *task);
void lntd_async_pool_complete(struct lntd_async_pool *pool,
struct lntd_async_task *task,
lntd_error err);
void lntd_async_pool_wait_on_poll(struct lntd_async_pool *pool,
struct lntd_async_waiter *waiter,
struct lntd_async_task *task,
lntd_ko ko, short flags);
lntd_error lntd_async_pool_wait(struct lntd_async_pool *pool,
struct lntd_async_result *resultp);
lntd_error lntd_async_pool_poll(struct lntd_async_pool *pool,
struct lntd_async_result *resultp);
lntd_error lntd_async_waiter_create(struct lntd_async_waiter **waiterp);
void lntd_async_waiter_destroy(struct lntd_async_waiter *waiter);
short lntd_async_waiter_revents(struct lntd_async_waiter *waiter);
lntd_error lntd_async_task_create(struct lntd_async_task **taskp,
void *data, lntd_async_type type);
void lntd_async_task_destroy(struct lntd_async_task *task);
void lntd_async_task_cancel(struct lntd_async_task *task);
void lntd_async_task_submit(struct lntd_async_pool *pool,
struct lntd_async_task *task,
union lntd_async_ck task_ck,
void *userstate);
void *lntd_async_task_data(struct lntd_async_task *task);
#endif /* LNTD_ASYNCH_H */
|
mstewartgallus/linted | src/env/env-windows.c | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/mem.h"
#include "lntd/utf.h"
#include "lntd/util.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <winerror.h>
static void lock(void);
static void unlock(void);
lntd_error lntd_env_set(char const *key, char const *value,
_Bool overwrite)
{
lntd_error err = 0;
wchar_t *key_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(key, &xx);
if (err != 0)
return err;
key_utf2 = xx;
}
wchar_t *value_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(value, &xx);
if (err != 0)
goto free_key;
value_utf2 = xx;
}
lock();
if (!overwrite) {
size_t size;
{
size_t xx;
_wgetenv_s(&xx, 0, 0U, key_utf2);
size = xx;
}
if (size != 0U)
goto unlock;
}
if (_wputenv_s(key_utf2, value_utf2) != 0)
err = LNTD_ERROR_OUT_OF_MEMORY;
unlock:
unlock();
lntd_mem_free(value_utf2);
free_key:
lntd_mem_free(key_utf2);
return err;
}
lntd_error lntd_env_get(char const *key, char **valuep)
{
lntd_error err = 0;
wchar_t *key_utf2;
{
wchar_t *xx;
err = lntd_utf_1_to_2(key, &xx);
if (err != 0)
return err;
key_utf2 = xx;
}
lock();
wchar_t *buffer = 0;
{
wchar_t *xx = 0;
size_t yy = 0U;
errno_t result = _wdupenv_s(&xx, &yy, key_utf2);
switch (result) {
case 0:
break;
case EINVAL:
/* Work around a bug in Wine or Windows NT */
break;
default:
err = LNTD_ERROR_OUT_OF_MEMORY;
goto unlock;
}
buffer = xx;
}
unlock:
unlock();
lntd_mem_free(key_utf2);
if (err != 0)
goto free_buffer;
char *value;
if (0 == buffer) {
value = 0;
} else {
char *xx;
err = lntd_utf_2_to_1(buffer, &xx);
if (err != 0)
goto free_buffer;
value = xx;
}
*valuep = value;
free_buffer:
lntd_mem_free(buffer);
return err;
}
static INIT_ONCE mutex_init_once = INIT_ONCE_STATIC_INIT;
static CRITICAL_SECTION mutex;
static void lock(void)
{
bool pending;
{
BOOL xx;
InitOnceBeginInitialize(&mutex_init_once, 0, &xx, 0);
pending = xx;
}
if (!pending)
goto lock;
InitializeCriticalSection(&mutex);
InitOnceComplete(&mutex_init_once, 0, 0);
lock:
EnterCriticalSection(&mutex);
}
static void unlock(void)
{
LeaveCriticalSection(&mutex);
}
|
mstewartgallus/linted | include/lntd/ko-windows.h | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_KO_H
#error this header should never be included directly
#endif
/* IWYU pragma: private, include "lntd/ko.h" */
/* Use a fake type to give a little more type safety. */
struct lntd_ko_;
typedef struct lntd_ko_ *lntd_ko;
#define LNTD_KO_CWD ((lntd_ko)-1)
#define LNTD_KO_STDIN lntd_ko__get_stdin()
#define LNTD_KO_STDOUT lntd_ko__get_stdout()
#define LNTD_KO_STDERR lntd_ko__get_stderr()
lntd_ko lntd_ko__get_stdin(void);
lntd_ko lntd_ko__get_stdout(void);
lntd_ko lntd_ko__get_stderr(void);
|
mstewartgallus/linted | include/lntd/ptrace.h | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_PTRACE_H
#define LNTD_PTRACE_H
#include "lntd/error.h"
#include "lntd/proc.h"
#include "lntd/util.h"
#include <stdint.h>
#if defined HAVE_POSIX_API
#include <sys/ptrace.h>
#endif
static inline lntd_error lntd_ptrace_detach(lntd_proc pid, int signo);
static inline lntd_error lntd_ptrace_setoptions(lntd_proc pid,
unsigned options);
static inline lntd_error lntd_ptrace_geteventmsg(lntd_proc pid,
unsigned long *msg);
static inline lntd_error lntd_ptrace_getsiginfo(lntd_proc pid,
void *infop);
static inline lntd_error lntd_ptrace_seize(lntd_proc pid,
uint_fast32_t options);
static inline lntd_error lntd_ptrace_cont(lntd_proc pid, int signo);
#ifdef PT_DETACH
static inline lntd_error lntd_ptrace_detach(lntd_proc pid, int signo)
{
lntd_error err;
if (-1 == ptrace(PT_DETACH, (pid_t)pid, (void *)0,
(void *)(intptr_t)signo)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PT_SETOPTIONS
static inline lntd_error lntd_ptrace_setoptions(lntd_proc pid,
unsigned options)
{
lntd_error err;
if (-1 == ptrace(PT_SETOPTIONS, (pid_t)pid, (void *)0,
(void *)(uintptr_t)options)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PT_GETEVENTMSG
static inline lntd_error lntd_ptrace_geteventmsg(lntd_proc pid,
unsigned long *msg)
{
lntd_error err;
if (-1 == ptrace(PT_GETEVENTMSG, (pid_t)pid, (void *)0,
(void *)(uintptr_t)msg)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PT_GETSIGINFO
static inline lntd_error lntd_ptrace_getsiginfo(lntd_proc pid,
void *infop)
{
lntd_error err;
if (-1 == ptrace(PT_GETSIGINFO, (pid_t)pid, (void *)0, infop)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PTRACE_SEIZE
static inline lntd_error lntd_ptrace_seize(lntd_proc pid,
uint_fast32_t options)
{
lntd_error err;
if (-1 == ptrace(PTRACE_SEIZE, (pid_t)pid, (void *)0,
(void *)(uintptr_t)options)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#ifdef PT_CONTINUE
static inline lntd_error lntd_ptrace_cont(lntd_proc pid, int signo)
{
lntd_error err;
if (-1 == ptrace(PT_CONTINUE, (pid_t)pid, (void *)0,
(void *)(intptr_t)signo)) {
err = errno;
LNTD_ASSUME(err != 0);
return err;
}
return 0;
}
#endif
#endif /* LNTD_PTRACE_H */
|
mstewartgallus/linted | include/lntd/unit.h | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_UNIT_H
#define LNTD_UNIT_H
#include "lntd/error.h"
#include "lntd/proc.h"
#include "lntd/sched.h"
#include <stddef.h>
#include <stdint.h>
/**
* @file
*
* Units.
*/
enum { LNTD_UNIT_NAME_MAX = 128 };
#define LNTD_UNIT_NAME_MAX ((unsigned)LNTD_UNIT_NAME_MAX)
enum { LNTD_UNIT_TYPE_SOCKET, LNTD_UNIT_TYPE_SERVICE };
typedef unsigned char lntd_unit_type;
enum { LNTD_UNIT_SOCKET_TYPE_DIR,
LNTD_UNIT_SOCKET_TYPE_FILE,
LNTD_UNIT_SOCKET_TYPE_FIFO };
typedef unsigned char lntd_unit_socket_type;
struct lntd_unit_db;
struct lntd_unit;
struct lntd_unit_service;
struct lntd_unit_socket;
lntd_error lntd_unit_db_create(struct lntd_unit_db **unitsp);
void lntd_unit_db_destroy(struct lntd_unit_db *units);
lntd_error lntd_unit_db_add_unit(struct lntd_unit_db *units,
struct lntd_unit **unitp);
size_t lntd_unit_db_size(struct lntd_unit_db *units);
struct lntd_unit *lntd_unit_db_get_unit(struct lntd_unit_db *units,
size_t ii);
struct lntd_unit *
lntd_unit_db_get_unit_by_name(struct lntd_unit_db *unit,
char const *name);
lntd_error lntd_unit_name(lntd_proc pid,
char name[static LNTD_UNIT_NAME_MAX + 1U]);
lntd_error lntd_unit_pid(lntd_proc *pidp, lntd_proc manager_pid,
char const *name);
struct lntd_unit_socket {
char const *path;
int_least32_t fifo_size;
lntd_unit_socket_type type;
};
struct lntd_unit_service {
char const *const *command;
char const *const *environment;
char const *fstab;
char const *chdir_path;
int_least64_t timer_slack_nsec;
int_least64_t limit_no_file;
int_least64_t limit_msgqueue;
int_least64_t limit_locks;
int_least64_t limit_memlock;
int priority;
_Bool has_timer_slack_nsec : 1U;
_Bool has_priority : 1U;
_Bool has_limit_no_file : 1U;
_Bool has_limit_msgqueue : 1U;
_Bool has_limit_locks : 1U;
_Bool has_limit_memlock : 1U;
_Bool clone_newuser : 1U;
_Bool clone_newcgroup : 1U;
_Bool clone_newpid : 1U;
_Bool clone_newipc : 1U;
_Bool clone_newnet : 1U;
_Bool clone_newns : 1U;
_Bool clone_newuts : 1U;
_Bool no_new_privs : 1U;
_Bool seccomp : 1U;
};
struct lntd_unit {
char *name;
lntd_unit_type type;
union {
struct lntd_unit_socket socket;
struct lntd_unit_service service;
} lntd_unit_u;
};
#endif /* LNTD_UNIT_H */
|
mstewartgallus/linted | src/stack/test_stack.c | <reponame>mstewartgallus/linted<filename>src/stack/test_stack.c
/*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#include "lntd/error.h"
#include "lntd/log.h"
#include "lntd/node.h"
#include "lntd/stack.h"
#include "lntd/start.h"
#include "lntd/util.h"
#include <stddef.h>
#include <stdlib.h>
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-stack-test"};
static unsigned char lntd_start_main(char const *process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
struct lntd_stack *stack;
{
struct lntd_stack *xx;
err = lntd_stack_create(&xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_stack_create: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
stack = xx;
}
static struct lntd_node nodes[20U];
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(nodes); ++ii) {
lntd_stack_send(stack, &nodes[ii]);
}
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(nodes); ++ii) {
struct lntd_node *xx;
err = lntd_stack_try_recv(stack, &xx);
if (err != 0) {
lntd_log(LNTD_LOG_ERROR,
"lntd_stack_try_recv: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
lntd_stack_destroy(stack);
return EXIT_SUCCESS;
}
|
mstewartgallus/linted | src/async/async-windows.c | /*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "config.h"
#define _WIN32_WINNT 0x0600
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "lntd/async.h"
#include "lntd/channel.h"
#include "lntd/io.h"
#include "lntd/mem.h"
#include "lntd/node.h"
#include "lntd/proc.h"
#include "lntd/sched.h"
#include "lntd/signal.h"
#include "lntd/stack.h"
#include "lntd/util.h"
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <windows.h>
#include <winsock2.h>
#define UPCAST(X) ((void *)(X))
#define DOWNCAST(T, X) ((T *)(X))
/**
* A one reader to many writers queue. Should be able to retrieve
* many values at once. As all writes are a direct result of
* submitted commands there is no need to worry about it growing
* too large.
*/
struct completion_queue;
static lntd_error
completion_queue_create(struct completion_queue **queuep);
static void complete_task(struct completion_queue *queue,
struct lntd_async_task *task);
static lntd_error completion_recv(struct completion_queue *queue,
struct lntd_async_task **taskp);
static lntd_error completion_try_recv(struct completion_queue *queue,
struct lntd_async_task **taskp);
static void completion_queue_destroy(struct completion_queue *queue);
struct job_queue;
static lntd_error job_queue_create(struct job_queue **queuep);
static void job_submit(struct job_queue *queue,
struct lntd_async_task *task);
static lntd_error job_recv(struct job_queue *queue,
struct lntd_async_task **taskp);
static void job_queue_destroy(struct job_queue *queue);
struct worker_queue;
static lntd_error worker_queue_create(struct worker_queue **queuep);
static lntd_error worker_try_submit(struct worker_queue *queue,
struct lntd_async_task *task);
static lntd_error worker_recv(struct worker_queue *queue,
struct lntd_async_task **taskp);
static void worker_queue_destroy(struct worker_queue *queue);
struct waiter_queue;
static lntd_error waiter_queue_create(struct waiter_queue **queuep);
static void waiter_submit(struct waiter_queue *queue,
struct lntd_async_waiter *waiter);
static lntd_error waiter_recv(struct waiter_queue *queue,
struct lntd_async_waiter **waiterp);
static void waiter_queue_destroy(struct waiter_queue *queue);
struct worker_pool;
static lntd_error worker_pool_create(struct worker_pool **poolp,
struct job_queue *job_queue,
struct lntd_async_pool *pool,
unsigned max_tasks);
static void worker_pool_destroy(struct worker_pool *pool);
struct wait_manager;
static lntd_error wait_manager_create(struct wait_manager **managerp,
struct waiter_queue *waiter_queue,
struct lntd_async_pool *pool,
unsigned max_pollers);
static void wait_manager_destroy(struct wait_manager *manager);
struct canceller {
lntd_ko owner;
CRITICAL_SECTION lock;
bool *cancel_replier;
bool owned : 1U;
bool in_flight : 1U;
};
static void canceller_init(struct canceller *canceller);
static void canceller_start(struct canceller *canceller);
static void canceller_stop(struct canceller *canceller);
static void canceller_cancel(struct canceller *canceller);
static bool canceller_check_or_register(struct canceller *canceller,
lntd_ko self);
static bool canceller_check_and_unregister(struct canceller *canceller);
struct lntd_async_pool {
struct wait_manager *wait_manager;
struct worker_pool *worker_pool;
struct job_queue *job_queue;
struct waiter_queue *waiter_queue;
struct completion_queue *completion_queue;
};
struct lntd_async_task {
struct lntd_node parent;
struct canceller canceller;
void *data;
lntd_error err;
union lntd_async_ck task_ck;
void *userstate;
lntd_async_type type;
bool thread_canceller : 1U;
};
struct lntd_async_waiter {
struct lntd_node parent;
struct lntd_async_task *task;
lntd_ko ko;
short flags;
short revents;
bool thread_canceller : 1U;
};
lntd_error lntd_async_pool_create(struct lntd_async_pool **poolp,
unsigned max_tasks)
{
lntd_error err;
struct lntd_async_pool *pool;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *pool);
if (err != 0)
return err;
pool = xx;
}
struct waiter_queue *waiter_queue;
{
struct waiter_queue *xx;
err = waiter_queue_create(&xx);
if (err != 0)
goto free_pool;
waiter_queue = xx;
}
struct job_queue *job_queue;
{
struct job_queue *xx;
err = job_queue_create(&xx);
if (err != 0)
goto destroy_waiter_queue;
job_queue = xx;
}
struct completion_queue *completion_queue;
{
struct completion_queue *xx;
err = completion_queue_create(&xx);
if (err != 0)
goto destroy_job_queue;
completion_queue = xx;
}
struct wait_manager *wait_manager;
{
struct wait_manager *xx;
err = wait_manager_create(&xx, waiter_queue, pool,
max_tasks);
if (err != 0)
goto destroy_completion_queue;
wait_manager = xx;
}
struct worker_pool *worker_pool;
{
struct worker_pool *xx;
err =
worker_pool_create(&xx, job_queue, pool, max_tasks);
if (err != 0)
goto destroy_wait_manager;
worker_pool = xx;
}
pool->worker_pool = worker_pool;
pool->wait_manager = wait_manager;
pool->waiter_queue = waiter_queue;
pool->job_queue = job_queue;
pool->completion_queue = completion_queue;
*poolp = pool;
return 0;
destroy_wait_manager:
wait_manager_destroy(wait_manager);
destroy_completion_queue:
completion_queue_destroy(completion_queue);
destroy_job_queue:
job_queue_destroy(job_queue);
destroy_waiter_queue:
waiter_queue_destroy(waiter_queue);
free_pool:
lntd_mem_free(pool);
return err;
}
lntd_error lntd_async_pool_destroy(struct lntd_async_pool *pool)
{
struct wait_manager *wait_manager = pool->wait_manager;
struct worker_pool *worker_pool = pool->worker_pool;
struct job_queue *job_queue = pool->job_queue;
struct waiter_queue *waiter_queue = pool->waiter_queue;
struct completion_queue *completion_queue =
pool->completion_queue;
worker_pool_destroy(worker_pool);
wait_manager_destroy(wait_manager);
job_queue_destroy(job_queue);
waiter_queue_destroy(waiter_queue);
completion_queue_destroy(completion_queue);
lntd_mem_free(pool);
return 0;
}
void lntd_async_pool_resubmit(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
LNTD_ASSERT(pool != 0);
if (canceller_check_and_unregister(&task->canceller)) {
task->err = LNTD_ERROR_CANCELLED;
complete_task(pool->completion_queue, task);
return;
}
job_submit(pool->job_queue, task);
}
void lntd_async_pool_complete(struct lntd_async_pool *pool,
struct lntd_async_task *task,
lntd_error task_err)
{
canceller_stop(&task->canceller);
task->err = task_err;
complete_task(pool->completion_queue, task);
}
void lntd_async_pool_wait_on_poll(struct lntd_async_pool *pool,
struct lntd_async_waiter *waiter,
struct lntd_async_task *task,
lntd_ko ko, short flags)
{
LNTD_ASSERT(pool != 0);
if (canceller_check_and_unregister(&task->canceller)) {
task->err = LNTD_ERROR_CANCELLED;
complete_task(pool->completion_queue, task);
return;
}
waiter->task = task;
waiter->ko = ko;
waiter->flags = flags;
waiter_submit(pool->waiter_queue, waiter);
}
lntd_error lntd_async_pool_wait(struct lntd_async_pool *pool,
struct lntd_async_result *resultp)
{
LNTD_ASSERT_NOT_NULL(pool);
struct lntd_async_task *task;
lntd_error err = completion_recv(pool->completion_queue, &task);
if (0 == err) {
resultp->task_ck = task->task_ck;
resultp->err = task->err;
resultp->userstate = task->userstate;
}
return err;
}
lntd_error lntd_async_pool_poll(struct lntd_async_pool *pool,
struct lntd_async_result *resultp)
{
LNTD_ASSERT_NOT_NULL(pool);
struct lntd_async_task *task;
lntd_error err =
completion_try_recv(pool->completion_queue, &task);
if (0 == err) {
resultp->task_ck = task->task_ck;
resultp->err = task->err;
resultp->userstate = task->userstate;
}
return err;
}
lntd_error lntd_async_waiter_create(struct lntd_async_waiter **waiterp)
{
lntd_error err;
struct lntd_async_waiter *waiter;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *waiter);
if (err != 0)
return err;
waiter = xx;
}
waiter->revents = 0;
waiter->thread_canceller = false;
*waiterp = waiter;
return 0;
}
void lntd_async_waiter_destroy(struct lntd_async_waiter *waiter)
{
lntd_mem_free(waiter);
}
short lntd_async_waiter_revents(struct lntd_async_waiter *waiter)
{
short ev = waiter->revents;
waiter->revents = 0;
return ev;
}
lntd_error lntd_async_task_create(struct lntd_async_task **taskp,
void *data, lntd_async_type type)
{
lntd_error err;
struct lntd_async_task *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
canceller_init(&task->canceller);
task->data = data;
task->type = type;
task->err = LNTD_ERROR_INVALID_PARAMETER;
task->thread_canceller = false;
*taskp = task;
return 0;
}
void lntd_async_task_destroy(struct lntd_async_task *task)
{
lntd_mem_free(task);
}
void lntd_async_task_cancel(struct lntd_async_task *task)
{
canceller_cancel(&task->canceller);
}
void lntd_async_task_submit(struct lntd_async_pool *pool,
struct lntd_async_task *task,
union lntd_async_ck task_ck,
void *userstate)
{
LNTD_ASSERT(pool != 0);
task->task_ck = task_ck;
task->userstate = userstate;
canceller_start(&task->canceller);
job_submit(pool->job_queue, task);
}
union lntd_async_ck lntd_async_task_ck(struct lntd_async_task *task)
{
return task->task_ck;
}
lntd_error lntd_async_task_err(struct lntd_async_task *task)
{
return task->err;
}
void *lntd_async_task_data(struct lntd_async_task *task)
{
return task->data;
}
static DWORD WINAPI master_worker_routine(void *arg);
static DWORD WINAPI worker_routine(void *arg);
static void run_task(struct lntd_async_pool *pool,
struct lntd_async_task *task);
struct worker_pool;
struct worker {
struct lntd_async_pool *pool;
struct worker_queue *queue;
lntd_ko thread;
};
struct worker_pool {
struct lntd_async_pool *async_pool;
struct job_queue *job_queue;
struct worker_queue **worker_queues;
size_t worker_count;
lntd_ko master_thread;
struct worker workers[];
};
static lntd_error worker_pool_create(struct worker_pool **poolp,
struct job_queue *job_queue,
struct lntd_async_pool *async_pool,
unsigned max_tasks)
{
lntd_error err = 0;
struct worker_pool *pool;
size_t workers_count = max_tasks;
size_t workers_size = workers_count * sizeof pool->workers[0U];
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *pool + workers_size);
if (err != 0)
return err;
pool = xx;
}
size_t worker_queues_created = 0U;
for (; worker_queues_created < max_tasks;
++worker_queues_created) {
err = worker_queue_create(
&pool->workers[worker_queues_created].queue);
if (err != 0)
goto destroy_worker_queues;
}
pool->worker_count = workers_count;
pool->job_queue = job_queue;
pool->async_pool = async_pool;
size_t created_threads = 0U;
for (; created_threads < max_tasks; ++created_threads) {
struct worker *worker = &pool->workers[created_threads];
worker->pool = async_pool;
lntd_ko thread =
CreateThread(0, 0, worker_routine, worker, 0, 0);
if (INVALID_HANDLE_VALUE == thread) {
err = HRESULT_FROM_WIN32(GetLastError());
break;
}
worker->thread = thread;
}
if (err != 0)
goto destroy_threads;
{
lntd_ko thread = CreateThread(
0, 0, master_worker_routine, pool, 0, 0);
if (INVALID_HANDLE_VALUE == thread) {
err = HRESULT_FROM_WIN32(GetLastError());
goto destroy_threads;
}
pool->master_thread = thread;
}
*poolp = pool;
return 0;
destroy_threads:
for (size_t ii = 0U; ii < created_threads; ++ii) {
struct worker const *worker = &pool->workers[ii];
struct worker_queue *worker_queue = worker->queue;
lntd_ko thread = worker->thread;
for (;;) {
struct lntd_async_task task;
task.thread_canceller = true;
lntd_error try_err =
worker_try_submit(worker_queue, &task);
if (0 == try_err) {
switch (WaitForSingleObject(thread,
INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
default:
LNTD_ASSERT(false);
}
break;
}
CancelSynchronousIo(thread);
SwitchToThread();
}
}
destroy_worker_queues:
for (size_t ii = 0U; ii < worker_queues_created; ++ii)
worker_queue_destroy(pool->workers[ii].queue);
lntd_mem_free(pool);
return err;
}
static void worker_pool_destroy(struct worker_pool *pool)
{
struct job_queue *job_queue = pool->job_queue;
lntd_ko master_thread = pool->master_thread;
struct worker const *workers = pool->workers;
size_t worker_count = pool->worker_count;
{
struct lntd_async_task task;
task.thread_canceller = true;
job_submit(job_queue, &task);
switch (WaitForSingleObject(master_thread, INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
default:
LNTD_ASSERT(false);
}
}
for (size_t ii = 0U; ii < worker_count; ++ii)
worker_queue_destroy(workers[ii].queue);
lntd_mem_free(pool);
}
static DWORD WINAPI master_worker_routine(void *arg)
{
lntd_proc_name("async-worker-master");
struct worker_pool *pool = arg;
struct job_queue *job_queue = pool->job_queue;
struct worker const *workers = pool->workers;
size_t max_tasks = pool->worker_count;
for (;;) {
struct lntd_async_task *task;
{
struct lntd_async_task *xx;
job_recv(job_queue, &xx);
task = xx;
}
if (task->thread_canceller)
break;
for (size_t ii = 0U;; ii = (ii + 1U) % max_tasks) {
lntd_error err =
worker_try_submit(workers[ii].queue, task);
if (LNTD_ERROR_AGAIN == err)
continue;
LNTD_ASSERT(0 == err);
break;
}
}
for (size_t ii = 0U; ii < max_tasks; ++ii) {
struct worker *worker = &pool->workers[ii];
struct worker_queue *worker_queue = worker->queue;
lntd_ko thread = worker->thread;
for (;;) {
struct lntd_async_task task;
task.thread_canceller = true;
lntd_error err =
worker_try_submit(worker_queue, &task);
if (0 == err) {
switch (WaitForSingleObject(thread,
INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
default:
LNTD_ASSERT(false);
}
break;
}
CancelSynchronousIo(thread);
SwitchToThread();
}
}
return 0;
}
static DWORD WINAPI worker_routine(void *arg)
{
lntd_proc_name("async-worker");
struct worker *worker = arg;
struct lntd_async_pool *async_pool = worker->pool;
struct worker_queue *worker_queue = worker->queue;
for (;;) {
struct lntd_async_task *task;
{
struct lntd_async_task *xx;
worker_recv(worker_queue, &xx);
task = xx;
}
if (task->thread_canceller)
break;
lntd_ko self = worker->thread;
if (canceller_check_or_register(&task->canceller,
self)) {
lntd_async_pool_complete(async_pool, task,
LNTD_ERROR_CANCELLED);
continue;
}
run_task(async_pool, task);
}
return 0;
}
#pragma weak lntd_sched_do_idle
#pragma weak lntd_io_do_poll
#pragma weak lntd_io_do_read
#pragma weak lntd_io_do_write
#pragma weak lntd_signal_do_wait
#pragma weak lntd_sched_do_sleep_until
static void run_task(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
switch (task->type) {
case LNTD_ASYNCH_TASK_IDLE:
lntd_sched_do_idle(pool, task);
break;
case LNTD_ASYNCH_TASK_POLL:
lntd_io_do_poll(pool, task);
break;
case LNTD_ASYNCH_TASK_READ:
lntd_io_do_read(pool, task);
break;
case LNTD_ASYNCH_TASK_WRITE:
lntd_io_do_write(pool, task);
break;
case LNTD_ASYNCH_TASK_SIGNAL_WAIT:
lntd_signal_do_wait(pool, task);
break;
case LNTD_ASYNCH_TASK_SLEEP_UNTIL:
lntd_sched_do_sleep_until(pool, task);
break;
default:
LNTD_ASSUME_UNREACHABLE();
}
}
struct poller_queue;
static lntd_error poller_queue_create(struct poller_queue **queuep);
static lntd_error poller_try_submit(struct poller_queue *queue,
struct lntd_async_waiter *waiter);
static lntd_error poller_recv(struct poller_queue *queue,
struct lntd_async_waiter **waiterp);
static void poller_queue_destroy(struct poller_queue *queue);
struct wait_manager;
struct poller {
struct lntd_async_pool *pool;
struct poller_queue *queue;
lntd_ko thread;
};
struct wait_manager {
struct lntd_async_pool *async_pool;
struct waiter_queue *waiter_queue;
size_t poller_count;
bool stopped : 1U;
lntd_ko master_thread;
struct poller pollers[];
};
static DWORD WINAPI master_poller_routine(void *arg);
static DWORD WINAPI poller_routine(void *arg);
static lntd_error poll_one(lntd_ko ko, short events, short *revents);
static lntd_error wait_manager_create(
struct wait_manager **managerp, struct waiter_queue *waiter_queue,
struct lntd_async_pool *async_pool, unsigned max_pollers)
{
lntd_error err;
size_t created_threads = 0U;
struct wait_manager *manager;
size_t pollers_count = max_pollers;
size_t pollers_size =
pollers_count * sizeof manager->pollers[0U];
{
void *xx;
err =
lntd_mem_alloc(&xx, sizeof *manager + pollers_size);
if (err != 0)
return err;
manager = xx;
}
size_t poller_queues_created = 0U;
for (; poller_queues_created < max_pollers;
++poller_queues_created) {
err = poller_queue_create(
&manager->pollers[poller_queues_created].queue);
if (err != 0)
goto free_manager;
}
manager->stopped = false;
manager->poller_count = pollers_count;
manager->waiter_queue = waiter_queue;
manager->async_pool = async_pool;
for (; created_threads < max_pollers; ++created_threads) {
struct poller *poller =
&manager->pollers[created_threads];
poller->pool = async_pool;
lntd_ko thread =
CreateThread(0, 0, poller_routine, poller, 0, 0);
if (INVALID_HANDLE_VALUE == thread) {
err = HRESULT_FROM_WIN32(GetLastError());
break;
}
poller->thread = thread;
}
if (err != 0)
goto destroy_threads;
{
lntd_ko thread = CreateThread(
0, 0, master_poller_routine, manager, 0, 0);
if (INVALID_HANDLE_VALUE == thread) {
err = HRESULT_FROM_WIN32(GetLastError());
goto destroy_threads;
}
manager->master_thread = thread;
}
*managerp = manager;
return 0;
destroy_threads:
for (size_t ii = 0U; ii < created_threads; ++ii) {
struct poller const *poller = &manager->pollers[ii];
struct poller_queue *poller_queue = poller->queue;
lntd_ko thread = poller->thread;
for (;;) {
struct lntd_async_waiter waiter;
waiter.thread_canceller = true;
lntd_error try_err =
poller_try_submit(poller_queue, &waiter);
if (0 == try_err) {
switch (WaitForSingleObject(thread,
INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
default:
LNTD_ASSERT(false);
}
break;
}
CancelSynchronousIo(thread);
SwitchToThread();
}
}
for (size_t ii = 0U; ii < poller_queues_created; ++ii)
poller_queue_destroy(manager->pollers[ii].queue);
free_manager:
lntd_mem_free(manager);
return err;
}
static void wait_manager_destroy(struct wait_manager *manager)
{
struct waiter_queue *waiter_queue = manager->waiter_queue;
lntd_ko master_thread = manager->master_thread;
size_t poller_count = manager->poller_count;
struct poller const *pollers = manager->pollers;
{
struct lntd_async_waiter waiter;
waiter.thread_canceller = true;
waiter_submit(waiter_queue, &waiter);
switch (WaitForSingleObject(master_thread, INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
default:
LNTD_ASSERT(false);
}
}
for (size_t ii = 0U; ii < poller_count; ++ii)
poller_queue_destroy(pollers[ii].queue);
lntd_mem_free(manager);
}
static DWORD WINAPI master_poller_routine(void *arg)
{
lntd_proc_name("async-poller-master");
struct wait_manager *pool = arg;
struct waiter_queue *waiter_queue = pool->waiter_queue;
struct poller *pollers = pool->pollers;
size_t max_tasks = pool->poller_count;
for (;;) {
struct lntd_async_waiter *waiter;
{
struct lntd_async_waiter *xx;
waiter_recv(waiter_queue, &xx);
waiter = xx;
}
if (waiter->thread_canceller)
break;
for (size_t ii = 0U;; ii = (ii + 1U) % max_tasks) {
lntd_error err = poller_try_submit(
pollers[ii].queue, waiter);
if (LNTD_ERROR_AGAIN == err)
continue;
LNTD_ASSERT(0 == err);
break;
}
}
for (size_t ii = 0U; ii < max_tasks; ++ii) {
struct poller_queue *poller_queue = pollers[ii].queue;
lntd_ko thread = pollers[ii].thread;
for (;;) {
struct lntd_async_waiter waiter;
waiter.thread_canceller = true;
lntd_error err =
poller_try_submit(poller_queue, &waiter);
if (0 == err) {
switch (WaitForSingleObject(thread,
INFINITE)) {
case WAIT_OBJECT_0:
break;
case WAIT_FAILED:
default:
LNTD_ASSERT(false);
}
break;
}
CancelSynchronousIo(thread);
SwitchToThread();
}
}
return 0;
}
static DWORD WINAPI poller_routine(void *arg)
{
lntd_proc_name("async-poller");
struct poller *poller = arg;
struct lntd_async_pool *async_pool = poller->pool;
struct poller_queue *poller_queue = poller->queue;
lntd_error err = 0;
for (;;) {
struct lntd_async_waiter *waiter;
{
struct lntd_async_waiter *xx;
poller_recv(poller_queue, &xx);
waiter = xx;
}
if (waiter->thread_canceller)
break;
lntd_ko self = poller->thread;
struct lntd_async_task *task = waiter->task;
lntd_ko ko = waiter->ko;
unsigned short flags = waiter->flags;
if (canceller_check_or_register(&task->canceller,
self)) {
err = LNTD_ERROR_CANCELLED;
goto complete_task;
}
short revents;
{
short xx;
err = poll_one(ko, flags, &xx);
if (HRESULT_FROM_WIN32(WSAEINTR) == err)
goto wait_on_poll;
if (err != 0)
goto complete_task;
revents = xx;
}
if ((revents & POLLNVAL) != 0) {
err = LNTD_ERROR_INVALID_KO;
goto complete_task;
}
if ((revents & POLLERR) != 0) {
int xx;
int yy = sizeof xx;
if (-1 == getsockopt((SOCKET)ko, SOL_SOCKET,
SO_ERROR, (void *)&xx,
&yy)) {
err = HRESULT_FROM_WIN32(
WSAGetLastError());
goto complete_task;
}
err = xx;
/* If another poller got the error then we
* could get zero instead so just resubmit in
* that case.
*/
if (err != 0)
goto complete_task;
}
waiter->revents = revents;
lntd_async_pool_resubmit(async_pool, task);
continue;
complete_task:
lntd_async_pool_complete(async_pool, task, err);
continue;
wait_on_poll:
lntd_async_pool_wait_on_poll(async_pool, waiter, task,
ko, flags);
}
return 0;
}
static lntd_error poll_one(lntd_ko ko, short events, short *reventsp)
{
short revents;
{
struct pollfd pollfd = {.fd = (SOCKET)ko,
.events = events};
int poll_status = WSAPoll(&pollfd, 1U, -1);
if (-1 == poll_status)
goto poll_failed;
revents = pollfd.revents;
}
*reventsp = revents;
return 0;
poll_failed:
;
lntd_error err = HRESULT_FROM_WIN32(WSAGetLastError());
LNTD_ASSUME(err != 0);
return err;
}
/* struct complete_queue is just a fake */
static lntd_error
completion_queue_create(struct completion_queue **queuep)
{
lntd_error err;
struct lntd_stack *queue;
{
struct lntd_stack *xx;
err = lntd_stack_create(&xx);
if (err != 0)
return err;
queue = xx;
}
*queuep = (struct completion_queue *)queue;
return 0;
}
static void complete_task(struct completion_queue *queue,
struct lntd_async_task *task)
{
lntd_stack_send((struct lntd_stack *)queue, UPCAST(task));
}
static lntd_error completion_recv(struct completion_queue *queue,
struct lntd_async_task **taskp)
{
struct lntd_node *node;
lntd_stack_recv((struct lntd_stack *)queue, &node);
*taskp = DOWNCAST(struct lntd_async_task, node);
return 0;
}
static lntd_error completion_try_recv(struct completion_queue *queue,
struct lntd_async_task **taskp)
{
lntd_error err;
struct lntd_node *node;
{
struct lntd_node *xx;
err = lntd_stack_try_recv((struct lntd_stack *)queue,
&xx);
if (err != 0)
return err;
node = xx;
}
*taskp = DOWNCAST(struct lntd_async_task, node);
return 0;
}
static void completion_queue_destroy(struct completion_queue *queue)
{
lntd_stack_destroy((struct lntd_stack *)queue);
}
/* struct job_queue is just a fake */
static lntd_error job_queue_create(struct job_queue **queuep)
{
lntd_error err;
struct lntd_stack *queue;
{
struct lntd_stack *xx;
err = lntd_stack_create(&xx);
if (err != 0)
return err;
queue = xx;
}
*queuep = (struct job_queue *)queue;
return 0;
}
static void job_submit(struct job_queue *queue,
struct lntd_async_task *task)
{
lntd_stack_send((struct lntd_stack *)queue, UPCAST(task));
}
static lntd_error job_recv(struct job_queue *queue,
struct lntd_async_task **taskp)
{
struct lntd_node *node;
{
struct lntd_node *xx;
lntd_stack_recv((struct lntd_stack *)queue, &xx);
node = xx;
}
*taskp = DOWNCAST(struct lntd_async_task, node);
return 0;
}
static void job_queue_destroy(struct job_queue *queue)
{
lntd_stack_destroy((struct lntd_stack *)queue);
}
/* struct worker_queue is just a fake */
static lntd_error worker_queue_create(struct worker_queue **queuep)
{
lntd_error err;
struct lntd_channel *channel;
{
struct lntd_channel *xx;
err = lntd_channel_create(&xx);
if (err != 0)
return err;
channel = xx;
}
*queuep = (struct worker_queue *)channel;
return 0;
}
static lntd_error worker_try_submit(struct worker_queue *queue,
struct lntd_async_task *task)
{
LNTD_ASSERT(queue != 0);
LNTD_ASSERT(task != 0);
return lntd_channel_try_send((struct lntd_channel *)queue,
task);
}
static lntd_error worker_recv(struct worker_queue *queue,
struct lntd_async_task **taskp)
{
LNTD_ASSERT(queue != 0);
LNTD_ASSERT(taskp != 0);
struct lntd_async_task *task;
{
void *xx;
lntd_channel_recv((struct lntd_channel *)queue, &xx);
task = xx;
}
LNTD_ASSERT(task != 0);
*taskp = task;
return 0;
}
static void worker_queue_destroy(struct worker_queue *queue)
{
lntd_channel_destroy((struct lntd_channel *)queue);
}
/* struct waiter_queue is just a fake */
static lntd_error waiter_queue_create(struct waiter_queue **queuep)
{
lntd_error err;
struct lntd_stack *raw_queue;
{
struct lntd_stack *xx;
err = lntd_stack_create(&xx);
if (err != 0)
return err;
raw_queue = xx;
}
*queuep = (struct waiter_queue *)raw_queue;
return 0;
}
static void waiter_queue_destroy(struct waiter_queue *queue)
{
lntd_stack_destroy((struct lntd_stack *)queue);
}
static void waiter_submit(struct waiter_queue *queue,
struct lntd_async_waiter *waiter)
{
LNTD_ASSERT(queue != 0);
LNTD_ASSERT(waiter != 0);
lntd_stack_send((struct lntd_stack *)queue, UPCAST(waiter));
}
static lntd_error waiter_recv(struct waiter_queue *queue,
struct lntd_async_waiter **waiterp)
{
LNTD_ASSERT(queue != 0);
LNTD_ASSERT(waiterp != 0);
struct lntd_node *node;
{
struct lntd_node *xx;
lntd_stack_recv((struct lntd_stack *)queue, &xx);
node = xx;
}
*waiterp = DOWNCAST(struct lntd_async_waiter, node);
return 0;
}
/* struct poller_queue is just a fake */
static lntd_error poller_queue_create(struct poller_queue **queuep)
{
lntd_error err;
struct lntd_channel *channel;
{
struct lntd_channel *xx;
err = lntd_channel_create(&xx);
if (err != 0)
return err;
channel = xx;
}
*queuep = (struct poller_queue *)channel;
return 0;
}
static lntd_error poller_try_submit(struct poller_queue *queue,
struct lntd_async_waiter *waiter)
{
LNTD_ASSERT(queue != 0);
LNTD_ASSERT(waiter != 0);
return lntd_channel_try_send((struct lntd_channel *)queue,
waiter);
}
static lntd_error poller_recv(struct poller_queue *queue,
struct lntd_async_waiter **waiterp)
{
struct lntd_async_waiter *waiter;
{
void *xx;
lntd_channel_recv((struct lntd_channel *)queue, &xx);
waiter = xx;
}
LNTD_ASSERT(waiter != 0);
*waiterp = waiter;
return 0;
}
static void poller_queue_destroy(struct poller_queue *queue)
{
lntd_channel_destroy((struct lntd_channel *)queue);
}
static void canceller_init(struct canceller *canceller)
{
InitializeCriticalSection(&canceller->lock);
canceller->in_flight = false;
canceller->owned = false;
canceller->cancel_replier = 0;
}
static void canceller_start(struct canceller *canceller)
{
EnterCriticalSection(&canceller->lock);
LNTD_ASSERT(!canceller->in_flight);
LNTD_ASSERT(!canceller->owned);
canceller->in_flight = true;
canceller->owned = false;
LeaveCriticalSection(&canceller->lock);
}
static void canceller_stop(struct canceller *canceller)
{
EnterCriticalSection(&canceller->lock);
LNTD_ASSERT(canceller->owned);
LNTD_ASSERT(canceller->in_flight);
{
bool *cancel_replier = canceller->cancel_replier;
bool cancelled = cancel_replier != 0;
if (cancelled)
*cancel_replier = true;
canceller->cancel_replier = 0;
}
canceller->in_flight = false;
canceller->owned = false;
LeaveCriticalSection(&canceller->lock);
}
static void canceller_cancel(struct canceller *canceller)
{
bool cancel_reply = false;
bool in_flight;
{
EnterCriticalSection(&canceller->lock);
LNTD_ASSERT(0 == canceller->cancel_replier);
in_flight = canceller->in_flight;
if (in_flight) {
canceller->cancel_replier = &cancel_reply;
bool owned = canceller->owned;
if (owned)
CancelSynchronousIo(canceller->owner);
}
LeaveCriticalSection(&canceller->lock);
}
if (!in_flight)
return;
/* Yes, really, we do have to busy wait to prevent race
* conditions unfortunately */
bool cancel_replied;
do {
SwitchToThread();
EnterCriticalSection(&canceller->lock);
cancel_replied = cancel_reply;
if (!cancel_replied) {
bool owned = canceller->owned;
if (owned)
CancelSynchronousIo(canceller->owner);
}
LeaveCriticalSection(&canceller->lock);
} while (!cancel_replied);
}
static bool canceller_check_or_register(struct canceller *canceller,
lntd_ko self)
{
bool cancelled;
EnterCriticalSection(&canceller->lock);
{
cancelled = canceller->cancel_replier != 0;
/* Don't actually complete the cancellation if
* cancelled and let the completion do that.
*/
canceller->owner = self;
canceller->owned = true;
}
LeaveCriticalSection(&canceller->lock);
return cancelled;
}
static bool canceller_check_and_unregister(struct canceller *canceller)
{
bool cancelled;
EnterCriticalSection(&canceller->lock);
LNTD_ASSERT(canceller->in_flight);
LNTD_ASSERT(canceller->owned);
canceller->owned = false;
{
bool *cancel_replier = canceller->cancel_replier;
cancelled = cancel_replier != 0;
if (cancelled)
*cancel_replier = true;
canceller->cancel_replier = 0;
}
LeaveCriticalSection(&canceller->lock);
return cancelled;
}
|
mstewartgallus/linted | include/lntd/rpc.h | <filename>include/lntd/rpc.h
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_RPC_H
#define LNTD_RPC_H
#include <stdint.h>
#include <string.h>
/**
* @file
*
* Converts native numbers to lists of bytes.
*/
#define LNTD_RPC_UINT32_SIZE 4U
#define LNTD_RPC_INT32_SIZE 4U
static inline void lntd_rpc_pack_uint32(uint_fast32_t fast, char *buf)
{
uint_fast16_t low = ((uintmax_t)fast) & 0xFFFFU;
uint_fast16_t high = (((uintmax_t)fast) >> 16U) & 0xFFFFU;
unsigned char bytes[LNTD_RPC_UINT32_SIZE] = {
((uintmax_t)low) & 0xFFU, (((uintmax_t)low) >> 8U) & 0xFFU,
((uintmax_t)high) & 0xFFU,
(((uintmax_t)high) >> 8U) & 0xFFU};
memcpy(buf, bytes, sizeof bytes);
}
static inline uint_fast32_t lntd_rpc_unpack_uint32(char const *buf)
{
unsigned char pos_bytes[LNTD_RPC_UINT32_SIZE];
memcpy(pos_bytes, buf, sizeof pos_bytes);
uint_fast16_t low = ((uintmax_t)pos_bytes[0U]) |
(((uintmax_t)pos_bytes[1U]) << 8U);
uint_fast16_t high = ((uintmax_t)pos_bytes[2U]) |
(((uintmax_t)pos_bytes[3U]) << 8U);
uint_fast32_t positive =
((uintmax_t)low) | (((uintmax_t)high) << 16U);
return positive;
}
#endif /* LNTD_RPC_H */
|
mstewartgallus/linted | include/lntd/log.h | <gh_stars>0
/*
* Copyright 2014 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_LOG_H
#define LNTD_LOG_H
#include "lntd/util.h"
/**
* @file
*
* Abstracts over the system logger.
*/
enum { LNTD_LOG_ERROR = 3, LNTD_LOG_WARNING = 4, LNTD_LOG_INFO = 6 };
typedef unsigned char lntd_log_level;
void lntd_log_open(char const *ident);
/**
* @file
*
* @bug Does not sanitize strange UTF-8 or terminal control
* characters. If an attacker controlled string is inserted into
* the system log they can gain privileges. See also,
* http://marc.info/?l=bugtraq&m=104612710031920&q=p3 .
*/
void lntd_log(lntd_log_level log_level, char const *format, ...)
LNTD_FORMAT(__printf__, 2, 3);
#endif /* LNTD_LOG_H */
|
mstewartgallus/linted | src/dir/dir-posix.c | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/dir.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/util.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <sys/stat.h>
lntd_error lntd_dir_create(lntd_ko *kop, lntd_ko dirko,
char const *pathname, unsigned long flags,
mode_t mode)
{
lntd_error err;
int fd = -1;
if (dirko > INT_MAX && dirko != LNTD_KO_CWD)
return EINVAL;
if (0 == kop) {
if (flags != 0U)
return EINVAL;
int mydirfd;
if (LNTD_KO_CWD == dirko) {
mydirfd = AT_FDCWD;
} else if (dirko > INT_MAX) {
return EINVAL;
} else {
mydirfd = dirko;
}
if (-1 == mkdirat(mydirfd, pathname, mode)) {
err = errno;
LNTD_ASSUME(err != 0);
if (EEXIST == err)
return 0;
return err;
}
return 0;
}
if ((flags & ~LNTD_DIR_ONLY) != 0U)
return EINVAL;
bool dir_only = (flags & LNTD_DIR_ONLY) != 0U;
unsigned long oflags = 0U;
if (dir_only)
oflags |= LNTD_KO_DIRECTORY;
char *pathnamedir;
{
char *xx;
err = lntd_path_dir(&xx, pathname);
if (err != 0)
return err;
pathnamedir = xx;
}
char *pathnamebase;
{
char *xx;
err = lntd_path_base(&xx, pathname);
if (err != 0)
goto free_pathnamedir;
pathnamebase = xx;
}
/* To prevent concurrency issues with the directory pointed to
* by pathnamedir being deleted or mounted over we need to be
* able to open a file descriptor to it.
*/
lntd_ko realdir;
{
lntd_ko xx;
err = lntd_ko_open(&xx, dirko, pathnamedir, oflags);
if (err != 0)
goto free_pathnamebase;
realdir = xx;
}
make_directory:
if (-1 == mkdirat(realdir, pathnamebase, mode)) {
err = errno;
LNTD_ASSUME(err != 0);
/* We can't simply turn this test into an error so we
* can add a LNTD_DIR_EXCL flag because the
* directory could be removed by a privileged tmp
* cleaner style program and then created by an enemy.
*/
if (EEXIST == err)
goto open_directory;
goto close_realdir;
}
open_directory : {
lntd_ko xx;
err =
lntd_ko_open(&xx, realdir, pathnamebase, LNTD_KO_DIRECTORY);
if (ENOENT == err)
goto make_directory;
if (err != 0)
goto free_pathnamebase;
fd = xx;
}
close_realdir : {
lntd_error close_err = lntd_ko_close(realdir);
LNTD_ASSERT(close_err != EBADF);
if (0 == err)
err = close_err;
}
free_pathnamebase:
lntd_mem_free(pathnamebase);
free_pathnamedir:
lntd_mem_free(pathnamedir);
if (err != 0) {
if (fd != -1) {
lntd_error close_err = lntd_ko_close(fd);
LNTD_ASSERT(close_err != EBADF);
}
return err;
}
*kop = fd;
return 0;
}
|
mstewartgallus/linted | include/lntd/stack.h | /*
* Copyright 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef LNTD_STACK_H
#define LNTD_STACK_H
#include "lntd/error.h"
struct lntd_node;
struct lntd_stack;
lntd_error lntd_stack_create(struct lntd_stack **stackp);
void lntd_stack_destroy(struct lntd_stack *stack);
void lntd_stack_send(struct lntd_stack *stack, struct lntd_node *node);
void lntd_stack_recv(struct lntd_stack *stack, struct lntd_node **node);
lntd_error lntd_stack_try_recv(struct lntd_stack *stack,
struct lntd_node **node);
#endif /* LNTD_STACK_H */
|
mstewartgallus/linted | src/linted-startup/linted-startup.c | <filename>src/linted-startup/linted-startup.c
/*
* Copyright 2013, 2014, 2015, 2016 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/admin.h"
#include "lntd/env.h"
#include "lntd/error.h"
#include "lntd/ko.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/start.h"
#include "lntd/str.h"
#include "lntd/unit.h"
#include "lntd/util.h"
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <wordexp.h>
struct conf;
static lntd_error
conf_system_default_limit_locks(struct conf *conf,
int_least64_t *limitp);
static lntd_error
conf_system_default_limit_memlock(struct conf *conf,
int_least64_t *limitp);
static lntd_error
conf_system_default_limit_msgqueue(struct conf *conf,
int_least64_t *limitp);
static lntd_error
conf_system_default_limit_nofile(struct conf *conf,
int_least64_t *limitp);
static lntd_error
conf_system_default_no_new_privileges(struct conf *conf,
bool *no_new_privs);
static lntd_error conf_system_default_seccomp(struct conf *conf,
bool *boolp);
static char const *const *
conf_system_default_pass_env(struct conf *conf);
static lntd_error conf_socket_listen_directory(struct conf *conf,
char const **strp);
static lntd_error conf_socket_listen_file(struct conf *conf,
char const **strp);
static lntd_error conf_socket_listen_fifo(struct conf *conf,
char const **strp);
static lntd_error conf_socket_pipe_size(struct conf *conf,
int_least64_t *intp);
static char const *const *conf_service_exec_start(struct conf *conf);
static char const *const *
conf_service_pass_environment(struct conf *conf);
static char const *const *conf_service_environment(struct conf *conf);
static char const *const *
conf_service_x_lntd_clone_flags(struct conf *conf);
static lntd_error conf_service_timer_slack_nsec(struct conf *conf,
int_least64_t *intp);
static lntd_error conf_service_priority(struct conf *conf,
int_least64_t *intp);
static lntd_error conf_service_limit_no_file(struct conf *conf,
int_least64_t *intp);
static lntd_error conf_service_limit_msgqueue(struct conf *conf,
int_least64_t *intp);
static lntd_error conf_service_limit_locks(struct conf *conf,
int_least64_t *intp);
static lntd_error conf_service_limit_memlock(struct conf *conf,
int_least64_t *intp);
static lntd_error conf_service_type(struct conf *conf,
char const **strp);
static lntd_error conf_service_no_new_privileges(struct conf *conf,
bool *boolp);
static lntd_error conf_service_seccomp(struct conf *conf, bool *boolp);
static lntd_error conf_service_x_lntd_fstab(struct conf *conf,
char const **strp);
static lntd_error conf_service_working_directory(struct conf *conf,
char const **strp);
struct conf_db;
struct conf;
typedef uint_fast64_t conf_section;
struct conf_db;
static lntd_error conf_db_create(struct conf_db **dbp);
static void conf_db_destroy(struct conf_db *db);
static lntd_error conf_db_add_conf(struct conf_db *db,
struct conf *conf);
static size_t conf_db_size(struct conf_db *db);
static struct conf *conf_db_get_conf(struct conf_db *db, size_t ii);
static lntd_error conf_create(struct conf **confp, char *file_name);
static lntd_error conf_parse_file(struct conf *conf, lntd_ko dir_ko,
char const *file_name);
static void conf_put(struct conf *conf);
static char const *conf_peek_name(struct conf *conf);
static lntd_error conf_add_section(struct conf *conf,
conf_section *sectionp,
char const *section_name);
static lntd_error conf_add_setting(struct conf *conf,
conf_section section,
char const *field,
char const *const *value);
enum { LNTD_SYSTEM_CONF_PATH, LNTD_UNIT_PATH };
static char const *const required_envs[] =
{[LNTD_SYSTEM_CONF_PATH] = "LINTED_SYSTEM_CONF_PATH",
[LNTD_UNIT_PATH] = "LINTED_UNIT_PATH"};
struct startup {
char const *system_conf_path;
char const *unit_path;
lntd_ko admin_in;
lntd_ko admin_out;
};
struct system_conf {
int_least64_t limit_locks;
int_least64_t limit_msgqueue;
int_least64_t limit_no_file;
int_least64_t limit_memlock;
char const *const *pass_env;
bool has_limit_locks : 1U;
bool has_limit_msgqueue : 1U;
bool has_limit_no_file : 1U;
bool has_limit_memlock : 1U;
bool has_no_new_privs : 1U;
bool has_seccomp : 1U;
bool no_new_privs : 1U;
bool seccomp : 1U;
};
static lntd_error startup_init(struct startup *startup,
char const *controller_path,
char const *updater_path,
char const *system_conf_path,
char const *unit_path);
static lntd_error startup_destroy(struct startup *startup);
static lntd_error startup_start(struct startup *startup);
static lntd_error startup_stop(struct startup *startup);
static lntd_error
populate_conf_db(struct conf_db *conf_db,
struct system_conf const *system_conf, lntd_ko cwd,
char const *unit_path);
static lntd_error populate_system_conf(struct conf_db *db, lntd_ko cwd,
char const *file_name);
static lntd_error
add_unit_dir_to_db(struct conf_db *db,
struct system_conf const *system_conf, lntd_ko cwd,
char const *dir_name);
static lntd_error socket_activate(struct conf *conf, lntd_ko admin_in,
lntd_ko admin_out);
static lntd_error
service_activate(struct system_conf const *system_conf,
struct conf *conf, lntd_ko admin_in,
lntd_ko admin_out);
static size_t null_list_size(char const *const *list);
static lntd_error filter_envvars(char ***resultsp,
char const *const *allowed_envvars);
static struct lntd_start_config const lntd_start_config = {
.canonical_process_name = PACKAGE_NAME "-startup", 0};
static unsigned char lntd_start_main(char const *const process_name,
size_t argc,
char const *const argv[])
{
lntd_error err = 0;
if (argc != 3U) {
lntd_log(LNTD_LOG_ERROR,
"missing some of 2 file operands");
return EXIT_FAILURE;
}
char const *system_conf_path;
char const *unit_path;
{
char *envs[LNTD_ARRAY_SIZE(required_envs)];
for (size_t ii = 0U;
ii < LNTD_ARRAY_SIZE(required_envs); ++ii) {
char const *req = required_envs[ii];
char *value;
{
char *xx;
err = lntd_env_get(req, &xx);
if (err != 0) {
lntd_log(
LNTD_LOG_ERROR,
"lntd_env_get: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
value = xx;
}
if (0 == value) {
lntd_log(LNTD_LOG_ERROR,
"%s is a required "
"environment variable",
req);
return EXIT_FAILURE;
}
envs[ii] = value;
}
system_conf_path = envs[LNTD_SYSTEM_CONF_PATH];
unit_path = envs[LNTD_UNIT_PATH];
}
char const *admin_in = argv[1U];
char const *admin_out = argv[2U];
static struct startup startup = {0};
err = startup_init(&startup, admin_in, admin_out,
system_conf_path, unit_path);
if (err != 0)
goto log_error;
err = startup_start(&startup);
if (err != 0)
goto destroy_startup;
lntd_error stop_err = startup_stop(&startup);
if (0 == err)
err = stop_err;
destroy_startup:
;
lntd_error destroy_err = startup_destroy(&startup);
if (0 == err)
err = destroy_err;
log_error:
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "%s", lntd_error_string(err));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static lntd_error startup_init(struct startup *startup,
char const *admin_in_path,
char const *admin_out_path,
char const *system_conf_path,
char const *unit_path)
{
lntd_error err = 0;
lntd_admin_in admin_in;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, admin_in_path,
LNTD_KO_RDWR);
if (err != 0)
return err;
admin_in = xx;
}
lntd_admin_out admin_out;
{
lntd_ko xx;
err = lntd_ko_open(&xx, LNTD_KO_CWD, admin_out_path,
LNTD_KO_RDWR);
if (err != 0)
goto close_admin_in;
admin_out = xx;
}
startup->admin_in = admin_in;
startup->admin_out = admin_out;
startup->system_conf_path = system_conf_path;
startup->unit_path = unit_path;
return 0;
close_admin_in:
lntd_ko_close(admin_in);
return err;
}
static lntd_error startup_destroy(struct startup *startup)
{
lntd_ko admin_in = startup->admin_in;
lntd_ko admin_out = startup->admin_out;
lntd_ko_close(admin_in);
lntd_ko_close(admin_out);
return 0;
}
static lntd_error startup_start(struct startup *startup)
{
char const *system_conf_path = startup->system_conf_path;
char const *unit_path = startup->unit_path;
lntd_ko admin_in = startup->admin_in;
lntd_ko admin_out = startup->admin_out;
lntd_error err = 0;
struct conf_db *conf_db;
{
struct conf_db *xx;
err = conf_db_create(&xx);
if (err != 0)
return err;
conf_db = xx;
}
for (char const *start = system_conf_path;;) {
char const *end = strchr(start, ':');
size_t len;
if (0 == end) {
len = strlen(start);
} else {
len = end - start;
}
char *file_name_dup;
{
char *xx;
err = lntd_str_dup_len(&xx, start, len);
if (err != 0)
goto destroy_conf_db;
file_name_dup = xx;
}
err = populate_system_conf(conf_db, LNTD_KO_CWD,
file_name_dup);
lntd_mem_free(file_name_dup);
if (err != 0)
goto destroy_conf_db;
if (0 == end)
break;
start = end + 1U;
}
struct conf *system_conf = 0;
for (size_t ii = 0U, size = conf_db_size(conf_db); ii < size;
++ii) {
struct conf *conf = conf_db_get_conf(conf_db, ii);
char const *file_name = conf_peek_name(conf);
if (0 == strcmp("system.conf", file_name)) {
system_conf = conf;
break;
}
}
if (0 == system_conf) {
err = LNTD_ERROR_FILE_NOT_FOUND;
goto destroy_conf_db;
}
struct system_conf system_conf_struct = {0};
err = conf_system_default_limit_locks(
system_conf, &system_conf_struct.limit_locks);
if (0 == err) {
system_conf_struct.has_limit_locks = true;
} else if (ENOENT == err) {
} else {
goto destroy_conf_db;
}
err = conf_system_default_limit_memlock(
system_conf, &system_conf_struct.limit_memlock);
if (0 == err) {
system_conf_struct.has_limit_memlock = true;
} else if (ENOENT == err) {
} else {
goto destroy_conf_db;
}
err = conf_system_default_limit_msgqueue(
system_conf, &system_conf_struct.limit_msgqueue);
if (0 == err) {
system_conf_struct.has_limit_msgqueue = true;
} else if (ENOENT == err) {
} else {
goto destroy_conf_db;
}
err = conf_system_default_limit_nofile(
system_conf, &system_conf_struct.limit_no_file);
if (0 == err) {
system_conf_struct.has_limit_no_file = true;
} else if (ENOENT == err) {
} else {
goto destroy_conf_db;
}
{
bool xx = false;
err = conf_system_default_no_new_privileges(system_conf,
&xx);
if (0 == err) {
system_conf_struct.no_new_privs = xx;
system_conf_struct.has_no_new_privs = true;
} else if (ENOENT == err) {
} else {
goto destroy_conf_db;
}
}
{
bool xx = false;
err = conf_system_default_seccomp(system_conf, &xx);
if (0 == err) {
system_conf_struct.seccomp = xx;
system_conf_struct.has_seccomp = true;
} else if (ENOENT == err) {
} else {
goto destroy_conf_db;
}
}
system_conf_struct.pass_env =
conf_system_default_pass_env(system_conf);
err = populate_conf_db(conf_db, &system_conf_struct,
LNTD_KO_CWD, unit_path);
if (err != 0)
goto destroy_conf_db;
size_t size = conf_db_size(conf_db);
for (size_t ii = 0U; ii < size; ++ii) {
struct conf *conf = conf_db_get_conf(conf_db, ii);
char const *file_name = conf_peek_name(conf);
char const *dot = strchr(file_name, '.');
char const *suffix = dot + 1U;
if (strcmp(suffix, "socket") != 0)
continue;
err = socket_activate(conf, admin_in, admin_out);
if (err != 0)
goto destroy_conf_db;
}
for (size_t ii = 0U; ii < size; ++ii) {
struct conf *conf = conf_db_get_conf(conf_db, ii);
char const *file_name = conf_peek_name(conf);
char const *dot = strchr(file_name, '.');
char const *suffix = dot + 1U;
if (strcmp(suffix, "service") != 0)
continue;
err = service_activate(&system_conf_struct, conf,
admin_in, admin_out);
if (err != 0)
goto destroy_conf_db;
}
return 0;
destroy_conf_db:
conf_db_destroy(conf_db);
return err;
}
static lntd_error startup_stop(struct startup *startup)
{
return 0;
}
static lntd_error
populate_conf_db(struct conf_db *db,
struct system_conf const *system_conf, lntd_ko cwd,
char const *unit_path)
{
lntd_error err = 0;
for (char const *dirstart = unit_path;;) {
char const *dirend = strchr(dirstart, ':');
size_t len;
if (0 == dirend) {
len = strlen(dirstart);
} else {
len = dirend - dirstart;
}
char *dir_name;
{
char *xx;
err = lntd_str_dup_len(&xx, dirstart, len);
if (err != 0)
return err;
dir_name = xx;
}
err =
add_unit_dir_to_db(db, system_conf, cwd, dir_name);
lntd_mem_free(dir_name);
if (err != 0)
return err;
if (0 == dirend)
break;
dirstart = dirend + 1U;
}
return 0;
}
static lntd_error populate_system_conf(struct conf_db *db, lntd_ko cwd,
char const *filename)
{
lntd_error err;
lntd_ko conf_ko;
{
lntd_ko xx;
err = lntd_ko_open(&xx, cwd, filename, LNTD_KO_RDONLY);
/* Just treat as an empty file */
if (LNTD_ERROR_FILE_NOT_FOUND == err)
return 0;
if (err != 0)
return err;
conf_ko = xx;
}
char *filename_dup;
{
char *xx;
err = lntd_str_dup(&xx, "system.conf");
if (err != 0)
goto close_ko;
filename_dup = xx;
}
struct conf *conf = 0;
{
struct conf *xx;
err = conf_create(&xx, filename_dup);
if (err != 0) {
lntd_mem_free(filename_dup);
goto close_ko;
}
conf = xx;
}
err = conf_parse_file(conf, conf_ko, filename);
if (err != 0)
goto free_conf;
err = conf_db_add_conf(db, conf);
free_conf:
if (err != 0)
conf_put(conf);
close_ko:
lntd_ko_close(conf_ko);
return err;
}
static lntd_error
add_unit_dir_to_db(struct conf_db *db,
struct system_conf const *system_conf, lntd_ko cwd,
char const *dir_name)
{
lntd_error err;
lntd_ko units_ko;
{
lntd_ko xx;
err =
lntd_ko_open(&xx, cwd, dir_name, LNTD_KO_DIRECTORY);
/* Just treat as an empty directory */
if (LNTD_ERROR_FILE_NOT_FOUND == err)
return 0;
if (err != 0)
return err;
units_ko = xx;
}
DIR *units_dir = fdopendir(units_ko);
if (0 == units_dir) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(units_ko);
}
if (LNTD_ERROR_FILE_NOT_FOUND == err)
return 0;
if (err != 0)
return err;
size_t files_count = 0U;
char **files = 0;
for (;;) {
errno = 0;
struct dirent const *entry = readdir(units_dir);
if (0 == entry) {
err = errno;
if (0 == err)
break;
goto free_file_names;
}
char const *name = entry->d_name;
if (0 == strcmp(".", name))
continue;
if (0 == strcmp("..", name))
continue;
char *name_copy;
{
char *xx;
err = lntd_str_dup(&xx, name);
if (err != 0)
goto free_file_names;
name_copy = xx;
}
size_t new_files_count = files_count + 1U;
char **new_files;
{
void *xx;
err = lntd_mem_realloc_array(&xx, files,
new_files_count,
sizeof files[0U]);
if (err != 0)
goto free_file_name;
new_files = xx;
}
new_files[files_count] = name_copy;
files = new_files;
files_count = new_files_count;
if (err != 0) {
free_file_name:
lntd_mem_free(name_copy);
goto free_file_names;
}
}
for (size_t ii = 0U; ii < files_count; ++ii) {
char *file_name = files[ii];
lntd_unit_type unit_type;
{
char const *dot = strchr(file_name, '.');
char const *suffix = dot + 1U;
if (0 == strcmp(suffix, "socket")) {
unit_type = LNTD_UNIT_TYPE_SOCKET;
} else if (0 == strcmp(suffix, "service")) {
unit_type = LNTD_UNIT_TYPE_SERVICE;
} else {
err = LNTD_ERROR_INVALID_PARAMETER;
goto free_file_names;
}
}
struct conf *conf = 0;
{
struct conf *xx;
err = conf_create(&xx, file_name);
if (err != 0)
goto close_unit_file;
conf = xx;
}
files[ii] = 0;
switch (unit_type) {
case LNTD_UNIT_TYPE_SOCKET:
/* Okay but we have no defaults for this */
break;
case LNTD_UNIT_TYPE_SERVICE: {
conf_section service;
{
conf_section xx;
err = conf_add_section(conf, &xx,
"Service");
if (err != 0)
goto close_unit_file;
service = xx;
}
if (system_conf->pass_env != 0) {
err = conf_add_setting(
conf, service, "PassEnvironment",
system_conf->pass_env);
if (err != 0)
goto close_unit_file;
}
if (system_conf->has_limit_no_file) {
char
limits[LNTD_NUMBER_TYPE_STRING_SIZE(
int_least64_t)];
sprintf(limits, "%" PRId64,
system_conf->limit_no_file);
char const *const expr[] = {limits, 0};
err = conf_add_setting(
conf, service, "LimitNOFILE", expr);
if (err != 0)
goto close_unit_file;
}
if (system_conf->has_limit_locks) {
char
limits[LNTD_NUMBER_TYPE_STRING_SIZE(
int_least64_t)];
sprintf(limits, "%" PRId64,
system_conf->limit_locks);
char const *const expr[] = {limits, 0};
err = conf_add_setting(
conf, service, "LimitLOCKS", expr);
if (err != 0)
goto close_unit_file;
}
if (system_conf->has_limit_msgqueue) {
char
limits[LNTD_NUMBER_TYPE_STRING_SIZE(
int_least64_t)];
sprintf(limits, "%" PRId64,
system_conf->limit_msgqueue);
char const *const expr[] = {limits, 0};
err = conf_add_setting(conf, service,
"LimitMSGQUEUE",
expr);
if (err != 0)
goto close_unit_file;
}
if (system_conf->has_limit_memlock) {
char
limits[LNTD_NUMBER_TYPE_STRING_SIZE(
int_least64_t)];
sprintf(limits, "%" PRId64,
system_conf->limit_memlock);
char const *const expr[] = {limits, 0};
err = conf_add_setting(conf, service,
"LimitMEMLOCK",
expr);
if (err != 0)
goto close_unit_file;
}
if (system_conf->has_no_new_privs) {
char const *const expr[] = {
system_conf->no_new_privs ? "true"
: "false",
0};
err = conf_add_setting(
conf, service, "NoNewPrivileges",
expr);
if (err != 0)
goto close_unit_file;
}
if (system_conf->has_seccomp) {
char const *const expr[] = {
system_conf->seccomp ? "true"
: "false",
0};
err = conf_add_setting(conf, service,
"Seccomp", expr);
if (err != 0)
goto close_unit_file;
}
break;
}
}
err = conf_parse_file(conf, units_ko, file_name);
close_unit_file:
if (err != 0)
goto free_unit;
err = conf_db_add_conf(db, conf);
free_unit:
if (err != 0)
conf_put(conf);
}
free_file_names:
for (size_t ii = 0U; ii < files_count; ++ii)
lntd_mem_free(files[ii]);
lntd_mem_free(files);
if (-1 == closedir(units_dir)) {
if (0 == err) {
err = errno;
LNTD_ASSUME(err != 0);
}
}
return err;
}
static lntd_error socket_activate(struct conf *conf, lntd_ko admin_in,
lntd_ko admin_out)
{
lntd_error err = 0;
char const *file_name = conf_peek_name(conf);
char const *dot = strchr(file_name, '.');
char *unit_name;
{
char *xx;
err = lntd_str_dup_len(&xx, file_name, dot - file_name);
if (err != 0)
return err;
unit_name = xx;
}
char const *listen_dir;
{
char const *xx = 0;
err = conf_socket_listen_directory(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
listen_dir = xx;
}
char const *listen_file;
{
char const *xx = 0;
err = conf_socket_listen_file(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
listen_file = xx;
}
char const *listen_fifo;
{
char const *xx = 0;
err = conf_socket_listen_fifo(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
listen_fifo = xx;
}
int fifo_size;
bool have_fifo_size;
{
int_least64_t xx = -1;
err = conf_socket_pipe_size(conf, &xx);
if (0 == err) {
have_fifo_size = true;
} else if (ENOENT == err) {
have_fifo_size = false;
} else {
goto free_unit_name;
}
fifo_size = xx;
}
lntd_unit_socket_type socket_type;
char const *path = 0;
if (listen_dir != 0) {
socket_type = LNTD_UNIT_SOCKET_TYPE_DIR;
path = listen_dir;
}
if (listen_file != 0) {
if (path != 0)
return LNTD_ERROR_INVALID_PARAMETER;
socket_type = LNTD_UNIT_SOCKET_TYPE_FILE;
path = listen_file;
}
if (listen_fifo != 0) {
if (path != 0)
return LNTD_ERROR_INVALID_PARAMETER;
socket_type = LNTD_UNIT_SOCKET_TYPE_FIFO;
path = listen_fifo;
}
if (0 == path)
return LNTD_ERROR_INVALID_PARAMETER;
if (have_fifo_size) {
if (0 == listen_fifo)
return LNTD_ERROR_INVALID_PARAMETER;
}
{
struct lntd_admin_request request = {0};
request.type = LNTD_ADMIN_ADD_SOCKET;
struct lntd_admin_request_add_socket *xx =
&request.lntd_admin_request_u.add_socket;
xx->name = (char *)unit_name;
xx->path = (char *)path;
xx->fifo_size = fifo_size;
xx->sock_type = socket_type;
err = lntd_admin_in_send(admin_in, &request);
}
if (err != 0)
goto free_unit_name;
{
struct lntd_admin_reply xx;
err = lntd_admin_out_recv(admin_out, &xx);
if (err != 0)
goto free_unit_name;
}
free_unit_name:
lntd_mem_free(unit_name);
return err;
}
static lntd_error
service_activate(struct system_conf const *system_conf,
struct conf *conf, lntd_ko admin_in, lntd_ko admin_out)
{
lntd_error err = 0;
char const *file_name = conf_peek_name(conf);
char const *dot = strchr(file_name, '.');
char *unit_name;
{
char *xx = 0;
err = lntd_str_dup_len(&xx, file_name, dot - file_name);
if (err != 0)
return err;
unit_name = xx;
LNTD_ASSERT(unit_name != 0);
}
char const *const *command = conf_service_exec_start(conf);
char const *const *env_whitelist =
conf_service_pass_environment(conf);
char const *const *env = conf_service_environment(conf);
char const *const *clone_flags =
conf_service_x_lntd_clone_flags(conf);
char const *type;
{
char const *xx = 0;
err = conf_service_type(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
type = xx;
}
bool no_new_privs;
{
bool xx = false;
err = conf_service_no_new_privileges(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
no_new_privs = xx;
}
bool seccomp;
{
bool xx = false;
err = conf_service_seccomp(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
seccomp = xx;
}
char const *fstab;
{
char const *xx = 0;
err = conf_service_x_lntd_fstab(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
fstab = xx;
}
char const *chdir_path;
{
char const *xx = 0;
err = conf_service_working_directory(conf, &xx);
if (err != 0 && err != ENOENT)
goto free_unit_name;
chdir_path = xx;
}
int_least64_t timer_slack_nsec;
bool has_timer_slack_nsec;
{
int_least64_t xx = -1;
err = conf_service_timer_slack_nsec(conf, &xx);
if (0 == err) {
has_timer_slack_nsec = true;
} else if (ENOENT == err) {
has_timer_slack_nsec = false;
} else {
goto free_unit_name;
}
timer_slack_nsec = xx;
}
int_least64_t priority;
bool has_priority;
{
int_least64_t xx = -1;
err = conf_service_priority(conf, &xx);
if (0 == err) {
has_priority = true;
} else if (ENOENT == err) {
has_priority = false;
} else {
goto free_unit_name;
}
priority = xx;
}
int_least64_t limit_no_file;
bool has_limit_no_file;
{
int_least64_t xx = -1;
err = conf_service_limit_no_file(conf, &xx);
if (0 == err) {
has_limit_no_file = true;
} else if (ENOENT == err) {
has_limit_no_file = false;
} else {
goto free_unit_name;
}
limit_no_file = xx;
}
int_least64_t limit_msgqueue;
bool has_limit_msgqueue;
{
int_least64_t xx = -1;
err = conf_service_limit_msgqueue(conf, &xx);
if (0 == err) {
has_limit_msgqueue = true;
} else if (ENOENT == err) {
has_limit_msgqueue = false;
} else {
goto free_unit_name;
}
limit_msgqueue = xx;
}
int_least64_t limit_locks;
bool has_limit_locks;
{
int_least64_t xx = -1;
err = conf_service_limit_locks(conf, &xx);
if (0 == err) {
has_limit_locks = true;
} else if (ENOENT == err) {
has_limit_locks = false;
} else {
goto free_unit_name;
}
limit_locks = xx;
}
int_least64_t limit_memlock;
bool has_limit_memlock;
{
int_least64_t xx = -1;
err = conf_service_limit_memlock(conf, &xx);
if (0 == err) {
has_limit_memlock = true;
} else if (ENOENT == err) {
has_limit_memlock = false;
} else {
goto free_unit_name;
}
limit_memlock = xx;
}
if (0 == type || 0 == strcmp("simple", type)) {
/* simple type of service */
} else {
err = LNTD_ERROR_INVALID_PARAMETER;
goto free_unit_name;
}
if (0 == command) {
err = LNTD_ERROR_INVALID_PARAMETER;
goto free_unit_name;
}
bool clone_newuser = false;
bool clone_newcgroup = false;
bool clone_newpid = false;
bool clone_newipc = false;
bool clone_newnet = false;
bool clone_newns = false;
bool clone_newuts = false;
if (clone_flags != 0) {
for (size_t ii = 0U; clone_flags[ii] != 0; ++ii) {
char const *flag = clone_flags[ii];
if (0 == strcmp("CLONE_NEWUSER", flag)) {
clone_newuser = true;
} else if (0 ==
strcmp("CLONE_NEWCGROUP", flag)) {
clone_newcgroup = true;
} else if (0 == strcmp("CLONE_NEWPID", flag)) {
clone_newpid = true;
} else if (0 == strcmp("CLONE_NEWIPC", flag)) {
clone_newipc = true;
} else if (0 == strcmp("CLONE_NEWNET", flag)) {
clone_newnet = true;
} else if (0 == strcmp("CLONE_NEWNS", flag)) {
clone_newns = true;
} else if (0 == strcmp("CLONE_NEWUTS", flag)) {
clone_newuts = true;
} else {
return LNTD_ERROR_INVALID_PARAMETER;
}
}
}
if (0 == type) {
/* simple type of service */
} else if (0 == strcmp("simple", type)) {
/* simple type of service */
} else {
return LNTD_ERROR_INVALID_PARAMETER;
}
char **envvars;
{
char **xx = 0;
err = filter_envvars(&xx, env_whitelist);
if (err != 0)
goto free_unit_name;
LNTD_ASSERT(xx != 0);
envvars = xx;
}
if (env != 0) {
size_t envvars_size =
null_list_size((char const *const *)envvars);
for (size_t ii = 0U; env[ii] != 0; ++ii) {
{
void *xx = 0;
err = lntd_mem_realloc_array(
&xx, envvars, envvars_size + 2U,
sizeof envvars[0U]);
if (err != 0)
goto free_unit_name;
LNTD_ASSERT(xx != 0);
envvars = xx;
}
++envvars_size;
envvars[envvars_size] = 0;
{
char *yy = 0;
err = lntd_str_dup(&yy, env[ii]);
if (err != 0)
goto free_unit_name;
LNTD_ASSERT(yy != 0);
envvars[envvars_size - 1U] = yy;
}
}
}
char *service_name_setting;
{
char *xx = 0;
err = lntd_str_format(&xx, "LINTED_SERVICE=%s",
unit_name);
if (err != 0)
goto free_envvars;
LNTD_ASSERT(xx != 0);
service_name_setting = xx;
}
{
size_t envvars_size =
null_list_size((char const *const *)envvars);
size_t new_size = envvars_size + 2U;
LNTD_ASSERT(new_size > 0U);
{
void *xx = 0;
err = lntd_mem_realloc_array(
&xx, envvars, new_size, sizeof envvars[0U]);
if (err != 0)
goto envvar_allocate_failed;
LNTD_ASSERT(xx != 0);
envvars = xx;
goto envvar_allocate_succeeded;
}
envvar_allocate_failed:
lntd_mem_free(service_name_setting);
service_name_setting = 0;
goto free_envvars;
envvar_allocate_succeeded:
envvars[envvars_size] = service_name_setting;
envvars[envvars_size + 1U] = 0;
}
char const *const *environment = (char const *const *)envvars;
if (0 == fstab)
fstab = "";
if (0 == chdir_path)
chdir_path = "";
{
struct lntd_admin_request request = {0};
request.type = LNTD_ADMIN_ADD_UNIT;
struct lntd_admin_request_add_unit *xx =
&request.lntd_admin_request_u.add_unit;
xx->timer_slack_nsec =
has_timer_slack_nsec ? &timer_slack_nsec : 0;
xx->priority = has_priority ? &priority : 0;
xx->limit_no_file =
has_limit_no_file ? &limit_no_file : 0;
xx->limit_msgqueue =
has_limit_msgqueue ? &limit_msgqueue : 0;
xx->limit_locks = has_limit_locks ? &limit_locks : 0;
xx->limit_memlock =
has_limit_memlock ? &limit_memlock : 0;
xx->clone_newuser = clone_newuser;
xx->clone_newcgroup = clone_newcgroup;
xx->clone_newpid = clone_newpid;
xx->clone_newipc = clone_newipc;
xx->clone_newnet = clone_newnet;
xx->clone_newns = clone_newns;
xx->clone_newuts = clone_newuts;
xx->no_new_privs = no_new_privs;
xx->seccomp = seccomp;
xx->name = (char *)unit_name;
xx->fstab = (char *)fstab;
xx->chdir_path = (char *)chdir_path;
xx->command.command_len = null_list_size(command);
xx->command.command_val = (char **)command;
xx->environment.environment_len =
null_list_size(environment);
xx->environment.environment_val = (char **)environment;
err = lntd_admin_in_send(admin_in, &request);
}
if (err != 0)
goto free_envvars;
{
struct lntd_admin_reply xx;
err = lntd_admin_out_recv(admin_out, &xx);
if (err != 0)
goto free_envvars;
}
free_envvars:
;
size_t envvars_size =
null_list_size((char const *const *)envvars);
for (size_t ii = 0U; ii < envvars_size; ++ii) {
lntd_mem_free(envvars[ii]);
envvars[ii] = 0;
}
lntd_mem_free(envvars);
envvars = 0;
free_unit_name:
lntd_mem_free(unit_name);
unit_name = 0;
return err;
}
static size_t null_list_size(char const *const *list)
{
if (0 == list)
return 0U;
for (size_t ii = 0U;; ++ii)
if (0 == list[ii])
return ii;
}
extern char **environ;
static lntd_error filter_envvars(char ***result_envvarsp,
char const *const *allowed_envvars)
{
char **result_envvars;
lntd_error err;
if (0 == allowed_envvars) {
char const *const *envs = (char const *const *)environ;
size_t size = null_list_size(envs);
{
void *xx = 0;
err = lntd_mem_alloc_array(
&xx, size + 1U, sizeof result_envvars[0U]);
if (err != 0)
return err;
LNTD_ASSERT(xx != 0);
result_envvars = xx;
}
for (size_t ii = 0U; ii < size; ++ii) {
char const *input = envs[ii];
char *xx = 0;
err = lntd_str_dup(&xx, input);
if (err != 0)
goto free_result_envvars;
LNTD_ASSERT(xx != 0);
result_envvars[ii] = xx;
}
result_envvars[size] = 0;
*result_envvarsp = result_envvars;
return 0;
}
size_t allowed_envvars_size = null_list_size(allowed_envvars);
{
void *xx = 0;
err =
lntd_mem_alloc_array(&xx, allowed_envvars_size + 1U,
sizeof result_envvars[0U]);
if (err != 0)
return err;
LNTD_ASSERT(xx != 0);
result_envvars = xx;
}
size_t result_envvars_size = 0U;
for (size_t ii = 0U; ii < allowed_envvars_size; ++ii) {
char const *envvar_name = allowed_envvars[ii];
char *envvar_value;
{
char *xx = 0;
err = lntd_env_get(envvar_name, &xx);
if (err != 0)
goto free_result_envvars;
envvar_value = xx;
}
if (0 == envvar_value)
continue;
++result_envvars_size;
{
char *xx = 0;
err = lntd_str_format(&xx, "%s=%s", envvar_name,
envvar_value);
lntd_mem_free(envvar_value);
envvar_value = 0;
if (err != 0)
goto free_result_envvars;
LNTD_ASSERT(xx != 0);
result_envvars[result_envvars_size - 1U] = xx;
}
}
result_envvars[result_envvars_size] = 0;
*result_envvarsp = result_envvars;
return 0;
free_result_envvars:
for (size_t ii = 0U; ii < result_envvars_size; ++ii) {
lntd_mem_free(result_envvars[ii]);
result_envvars[ii] = 0;
}
lntd_mem_free(result_envvars);
result_envvars = 0;
return err;
}
static size_t string_list_size(char const *const *list);
enum { PARSER_ERROR,
PARSER_EOF,
PARSER_EMPTY_LINE,
PARSER_SECTION,
PARSER_VALUE };
struct parser {
wordexp_t expr;
FILE *file;
char *line_buffer;
size_t line_capacity;
char *section_name;
char *field;
unsigned char state;
};
struct parser_result_section {
char const *section_name;
};
struct parser_result_value {
char const *field;
char const *const *value;
};
union parser_result_union {
struct parser_result_section section;
struct parser_result_value value;
};
struct parser_result {
union parser_result_union result_union;
unsigned char state;
};
static void parser_init(struct parser *parser, FILE *file);
static lntd_error parser_get_line(struct parser *parser,
struct parser_result *resultp);
static lntd_error conf_parse_file(struct conf *conf, lntd_ko dir_ko,
char const *file_name)
{
lntd_error err = 0;
conf_section current_section;
lntd_ko conf_fd;
{
lntd_ko xx;
err = lntd_ko_open(&xx, dir_ko, file_name,
LNTD_KO_RDONLY);
if (err != 0)
return err;
conf_fd = xx;
}
FILE *conf_file = fdopen(conf_fd, "r");
if (0 == conf_file) {
err = errno;
LNTD_ASSUME(err != 0);
lntd_ko_close(conf_fd);
return err;
}
struct parser parser;
parser_init(&parser, conf_file);
for (;;) {
struct parser_result result;
err = parser_get_line(&parser, &result);
if (err != 0)
break;
switch (result.state) {
case PARSER_EOF:
goto free_parser;
/* Ignore empty lines */
case PARSER_EMPTY_LINE:
continue;
case PARSER_SECTION: {
conf_section xx;
err = conf_add_section(
conf, &xx,
result.result_union.section.section_name);
if (err != 0)
break;
current_section = xx;
break;
}
case PARSER_VALUE: {
err = conf_add_setting(
conf, current_section,
result.result_union.value.field,
result.result_union.value.value);
if (err != 0)
break;
}
}
}
free_parser:
switch (parser.state) {
case PARSER_VALUE:
lntd_mem_free(parser.field);
wordfree(&parser.expr);
break;
}
lntd_mem_free(parser.section_name);
lntd_mem_free(parser.line_buffer);
if (err != 0)
conf_put(conf);
if (EOF == fclose(conf_file)) {
if (0 == err) {
err = errno;
LNTD_ASSUME(err != 0);
}
}
return err;
}
static char const *const *
conf_find(struct conf *conf, char const *section, char const *field);
static lntd_error conf_find_str(struct conf *conf, char const *section,
char const *field, char const **strp);
static lntd_error conf_find_int(struct conf *conf, char const *section,
char const *field, int_least64_t *intp);
static lntd_error conf_find_bool(struct conf *conf, char const *section,
char const *field, _Bool *boolp);
static lntd_error conf_system_default_limit_locks(struct conf *conf,
int_least64_t *limitp)
{
return conf_find_int(conf, "Manager", "DefaultLimitLOCKS",
limitp);
}
static lntd_error
conf_system_default_limit_memlock(struct conf *conf,
int_least64_t *limitp)
{
return conf_find_int(conf, "Manager", "DefaultLimitMEMLOCK",
limitp);
}
static lntd_error
conf_system_default_limit_msgqueue(struct conf *conf,
int_least64_t *limitp)
{
return conf_find_int(conf, "Manager", "DefaultLimitMSGQUEUE",
limitp);
}
static lntd_error
conf_system_default_limit_nofile(struct conf *conf,
int_least64_t *limitp)
{
return conf_find_int(conf, "Manager", "DefaultLimitNOFILE",
limitp);
}
static lntd_error
conf_system_default_no_new_privileges(struct conf *conf,
bool *no_new_privs)
{
return conf_find_bool(conf, "Manager",
"X-LintedNoNewPrivileges", no_new_privs);
}
static lntd_error conf_system_default_seccomp(struct conf *conf,
bool *seccomp)
{
return conf_find_bool(conf, "Manager", "X-LintedSeccomp",
seccomp);
}
static char const *const *
conf_system_default_pass_env(struct conf *conf)
{
return conf_find(conf, "Manager", "X-LintedPassEnvironment");
}
static lntd_error conf_socket_listen_directory(struct conf *conf,
char const **strp)
{
return conf_find_str(conf, "Socket", "ListenDirectory", strp);
}
static lntd_error conf_socket_listen_file(struct conf *conf,
char const **strp)
{
return conf_find_str(conf, "Socket", "ListenFile", strp);
}
static lntd_error conf_socket_listen_fifo(struct conf *conf,
char const **strp)
{
return conf_find_str(conf, "Socket", "ListenFIFO", strp);
}
static lntd_error conf_socket_pipe_size(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Socket", "PipeSize", intp);
}
static char const *const *conf_service_exec_start(struct conf *conf)
{
return conf_find(conf, "Service", "ExecStart");
}
static char const *const *
conf_service_pass_environment(struct conf *conf)
{
return conf_find(conf, "Service", "PassEnvironment");
}
static char const *const *conf_service_environment(struct conf *conf)
{
return conf_find(conf, "Service", "Environment");
}
static char const *const *
conf_service_x_lntd_clone_flags(struct conf *conf)
{
return conf_find(conf, "Service", "X-LintedCloneFlags");
}
static lntd_error conf_service_timer_slack_nsec(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Service", "TimerSlackNSec", intp);
}
static lntd_error conf_service_priority(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Service", "Nice", intp);
}
static lntd_error conf_service_limit_no_file(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Service", "LimitNOFILE", intp);
}
static lntd_error conf_service_limit_msgqueue(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Service", "LimitMSGQUEUE", intp);
}
static lntd_error conf_service_limit_locks(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Service", "LimitLOCKS", intp);
}
static lntd_error conf_service_limit_memlock(struct conf *conf,
int_least64_t *intp)
{
return conf_find_int(conf, "Service", "LimitMEMLOCK", intp);
}
static lntd_error conf_service_type(struct conf *conf,
char const **strp)
{
return conf_find_str(conf, "Service", "Type", strp);
}
static lntd_error conf_service_no_new_privileges(struct conf *conf,
bool *boolp)
{
return conf_find_bool(conf, "Service", "NoNewPrivileges",
boolp);
}
static lntd_error conf_service_seccomp(struct conf *conf, bool *boolp)
{
return conf_find_bool(conf, "Service", "Seccomp", boolp);
}
static lntd_error conf_service_x_lntd_fstab(struct conf *conf,
char const **strp)
{
return conf_find_str(conf, "Service", "X-LintedFstab", strp);
}
static lntd_error conf_service_working_directory(struct conf *conf,
char const **strp)
{
return conf_find_str(conf, "Service", "WorkingDirectory", strp);
}
struct conf_db {
struct conf **confs;
size_t size;
};
static size_t string_hash(char const *str);
static lntd_error conf_db_create(struct conf_db **dbp)
{
struct conf_db *db;
{
void *xx;
lntd_error err = lntd_mem_alloc(&xx, sizeof *db);
if (err != 0)
return err;
db = xx;
}
db->size = 0U;
db->confs = 0;
*dbp = db;
return 0;
}
static void conf_db_destroy(struct conf_db *db)
{
size_t size = db->size;
struct conf **confs = db->confs;
for (size_t ii = 0U; ii < size; ++ii)
conf_put(confs[ii]);
lntd_mem_free(confs);
lntd_mem_free(db);
}
static lntd_error conf_db_add_conf(struct conf_db *db,
struct conf *conf)
{
struct conf **confs = db->confs;
size_t confs_size = db->size;
size_t new_confs_size = confs_size + 1U;
struct conf **new_confs;
{
void *xx;
lntd_error err = lntd_mem_realloc_array(
&xx, confs, new_confs_size, sizeof confs[0U]);
if (err != 0)
return err;
new_confs = xx;
}
new_confs[confs_size] = conf;
confs = new_confs;
confs_size = new_confs_size;
db->confs = confs;
db->size = confs_size;
return 0;
}
static size_t conf_db_size(struct conf_db *db)
{
return db->size;
}
static struct conf *conf_db_get_conf(struct conf_db *db, size_t ii)
{
return db->confs[ii];
}
struct conf_setting;
#define SETTING_BUCKETS_SIZE 1024U
struct conf_setting_bucket {
size_t settings_size;
struct conf_setting *settings;
};
struct conf_section {
size_t buckets_used;
struct conf_setting_bucket buckets[SETTING_BUCKETS_SIZE];
};
struct service {
int_least64_t limit_locks;
int_least64_t limit_msgqueue;
int_least64_t limit_no_file;
int_least64_t limit_memlock;
char const *const *pass_env;
bool has_limit_locks : 1U;
bool has_limit_msgqueue : 1U;
bool has_limit_no_file : 1U;
bool has_limit_memlock : 1U;
bool has_no_new_privs : 1U;
bool has_seccomp : 1U;
bool no_new_privs : 1U;
bool seccomp : 1U;
};
enum { SECTION_MANAGER,
SECTION_UNIT,
SECTION_SERVICE,
SECTION_SOCKET,
SECTION_COUNT };
enum { CONF_TYPE_MANAGER, CONF_TYPE_SERVICE, CONF_TYPE_SOCKET };
struct conf {
char *name;
unsigned long refcount;
unsigned char conf_type;
union {
struct conf_section manager;
struct {
struct conf_section unit;
struct conf_section service;
} service;
struct {
struct conf_section unit;
struct conf_section socket;
} socket;
} conf_u;
};
static void section_init(struct conf_section *section);
static void section_free(struct conf_section *section);
static lntd_error section_add(struct conf_section *section,
char const *field,
char const *const *additional_values);
static char const *const *section_find(struct conf_section *section,
char const *field);
static lntd_error conf_create(struct conf **confp, char *name)
{
lntd_error err = 0;
char const *dot = strchr(name, '.');
char const *suffix = dot + 1U;
unsigned char conf_type;
if (0 == strcmp(suffix, "socket")) {
conf_type = CONF_TYPE_SOCKET;
} else if (0 == strcmp(suffix, "service")) {
conf_type = CONF_TYPE_SERVICE;
} else if (0 == strcmp(suffix, "conf")) {
conf_type = CONF_TYPE_MANAGER;
} else {
return LNTD_ERROR_INVALID_PARAMETER;
}
struct conf *conf;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *conf);
if (err != 0)
return err;
conf = xx;
}
conf->name = name;
conf->conf_type = conf_type;
conf->refcount = 1;
switch (conf_type) {
case CONF_TYPE_MANAGER:
section_init(&conf->conf_u.manager);
break;
case CONF_TYPE_SERVICE:
section_init(&conf->conf_u.service.unit);
section_init(&conf->conf_u.service.service);
break;
case CONF_TYPE_SOCKET:
section_init(&conf->conf_u.socket.unit);
section_init(&conf->conf_u.socket.socket);
break;
}
*confp = conf;
return 0;
}
static void free_settings(struct conf_setting *settings,
size_t settings_size);
static void conf_put(struct conf *conf)
{
if (0 == conf)
return;
if (--conf->refcount != 0)
return;
switch (conf->conf_type) {
case CONF_TYPE_MANAGER:
section_free(&conf->conf_u.manager);
break;
case CONF_TYPE_SERVICE:
section_free(&conf->conf_u.service.unit);
section_free(&conf->conf_u.service.service);
break;
case CONF_TYPE_SOCKET:
section_free(&conf->conf_u.socket.unit);
section_free(&conf->conf_u.socket.socket);
break;
}
lntd_mem_free(conf->name);
lntd_mem_free(conf);
}
static char const *conf_peek_name(struct conf *conf)
{
return conf->name;
}
static lntd_error get_section(conf_section *sectionp, char const *name)
{
conf_section section_id;
if (0 == strcmp("Manager", name)) {
section_id = SECTION_MANAGER;
} else if (0 == strcmp("Unit", name)) {
section_id = SECTION_UNIT;
} else if (0 == strcmp("Service", name)) {
section_id = SECTION_SERVICE;
} else if (0 == strcmp("Socket", name)) {
section_id = SECTION_SOCKET;
} else {
return ENOENT;
}
*sectionp = section_id;
return 0;
}
static lntd_error conf_add_section(struct conf *conf,
conf_section *sectionp,
char const *section_name)
{
return get_section(sectionp, section_name);
}
struct conf_setting {
char *field;
char **value;
};
static char const *const *conf_find(struct conf *conf,
char const *section_name,
char const *field)
{
lntd_error err = 0;
conf_section section_id;
err = get_section(§ion_id, section_name);
if (err != 0)
return 0;
switch (conf->conf_type) {
case CONF_TYPE_MANAGER:
assert(SECTION_MANAGER == section_id);
return section_find(&conf->conf_u.manager, field);
case CONF_TYPE_SERVICE:
switch (section_id) {
case SECTION_UNIT:
return section_find(&conf->conf_u.service.unit,
field);
case SECTION_SERVICE:
return section_find(
&conf->conf_u.service.service, field);
default:
abort();
}
break;
case CONF_TYPE_SOCKET:
switch (section_id) {
case SECTION_UNIT:
return section_find(&conf->conf_u.socket.unit,
field);
case SECTION_SOCKET:
return section_find(&conf->conf_u.socket.socket,
field);
default:
abort();
}
break;
}
assert(0);
}
static lntd_error conf_find_str(struct conf *conf, char const *section,
char const *field, char const **strp)
{
char const *const *strs = conf_find(conf, section, field);
if (0 == strs)
return ENOENT;
char const *str = strs[0U];
if (0 == str)
return LNTD_ERROR_INVALID_PARAMETER;
if (strs[1U] != 0)
return LNTD_ERROR_INVALID_PARAMETER;
*strp = str;
return 0;
}
static lntd_error conf_find_int(struct conf *conf, char const *section,
char const *field, int_least64_t *intp)
{
char const *const *strs = conf_find(conf, section, field);
if (0 == strs)
return ENOENT;
char const *str = strs[0U];
if (0 == str)
return LNTD_ERROR_INVALID_PARAMETER;
if (strs[1U] != 0)
return LNTD_ERROR_INVALID_PARAMETER;
*intp = atoi(str);
return 0;
}
static lntd_error conf_find_bool(struct conf *conf, char const *section,
char const *field, _Bool *boolp)
{
char const *const *strs = conf_find(conf, section, field);
if (0 == strs)
return ENOENT;
char const *str = strs[0U];
if (0 == str)
return LNTD_ERROR_INVALID_PARAMETER;
if (strs[1U] != 0)
return LNTD_ERROR_INVALID_PARAMETER;
static char const *const yes_strs[] = {"1", "yes", "true",
"on"};
static char const *const no_strs[] = {"0", "no", "false",
"off"};
bool result;
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(yes_strs); ++ii) {
if (0 == strcmp(str, yes_strs[ii])) {
result = true;
goto return_result;
}
}
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(no_strs); ++ii) {
if (0 == strcmp(str, no_strs[ii])) {
result = false;
goto return_result;
}
}
return LNTD_ERROR_INVALID_PARAMETER;
return_result:
*boolp = result;
return 0;
}
static lntd_error conf_add_setting(struct conf *conf,
conf_section section_id,
char const *field,
char const *const *additional_values)
{
switch (conf->conf_type) {
case CONF_TYPE_MANAGER:
assert(SECTION_MANAGER == section_id);
return section_add(&conf->conf_u.manager, field,
additional_values);
case CONF_TYPE_SERVICE:
switch (section_id) {
case SECTION_UNIT:
return section_add(&conf->conf_u.service.unit,
field, additional_values);
case SECTION_SERVICE:
return section_add(
&conf->conf_u.service.service, field,
additional_values);
default:
abort();
}
break;
case CONF_TYPE_SOCKET:
switch (section_id) {
case SECTION_UNIT:
return section_add(&conf->conf_u.socket.unit,
field, additional_values);
case SECTION_SOCKET:
return section_add(&conf->conf_u.socket.socket,
field, additional_values);
default:
abort();
}
break;
}
assert(0);
}
static size_t string_list_size(char const *const *list)
{
size_t ii = 0U;
for (;; ++ii) {
if (0 == list[ii])
break;
}
return ii;
}
static size_t string_hash(char const *str)
{
size_t hash = 0U;
for (size_t ii = 0U; str[ii] != '\0'; ++ii)
hash = hash * 31U + (unsigned)str[ii];
return hash;
}
static void parser_init(struct parser *parser, FILE *file)
{
parser->file = file;
parser->line_buffer = 0;
parser->line_capacity = 0U;
parser->section_name = 0;
parser->state = PARSER_ERROR;
}
static lntd_error parser_get_line(struct parser *parser,
struct parser_result *result)
{
unsigned char state;
lntd_error err = 0;
char *line_buffer = parser->line_buffer;
size_t line_capacity = parser->line_capacity;
FILE *file = parser->file;
switch (parser->state) {
case PARSER_VALUE:
lntd_mem_free(parser->field);
wordfree(&parser->expr);
break;
}
ssize_t zz;
{
char *xx = line_buffer;
size_t yy = line_capacity;
errno = 0;
zz = getline(&xx, &yy, file);
if (zz < 0) {
/* May be 0 to indicate end of line */
err = errno;
if (0 == err) {
state = PARSER_EOF;
} else {
state = PARSER_ERROR;
}
goto set_values;
}
line_buffer = xx;
line_capacity = yy;
}
size_t line_size = zz;
if (0 == line_size) {
state = PARSER_EOF;
goto set_values;
}
if ('\n' == line_buffer[line_size - 1U])
--line_size;
if (0U == line_size) {
state = PARSER_EMPTY_LINE;
goto set_values;
}
switch (line_buffer[0U]) {
/* Ignore comments */
case ';':
case '#':
state = PARSER_EMPTY_LINE;
break;
case '[': {
if (line_buffer[line_size - 1U] != ']') {
err = LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
}
char *section_name;
{
char *xx;
err = lntd_str_dup_len(&xx, line_buffer + 1U,
line_size - 2U);
if (err != 0) {
state = PARSER_ERROR;
break;
}
section_name = xx;
}
lntd_mem_free(parser->section_name);
parser->section_name = section_name;
result->result_union.section.section_name =
section_name;
state = PARSER_SECTION;
break;
}
default: {
if (0 == parser->section_name) {
err = LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
}
size_t equals_position;
size_t whitespace_position;
size_t field_len;
for (size_t ii = 0U; ii < line_size; ++ii) {
switch (line_buffer[ii]) {
case '=':
equals_position = ii;
field_len = ii;
goto found_equal;
case ' ':
case '\t':
if (0U == ii) {
err =
LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
}
whitespace_position = ii;
field_len = ii;
goto found_whitespace;
case '\n':
err = LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
default:
break;
}
if (err != 0) {
state = PARSER_ERROR;
break;
}
}
err = LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
found_whitespace:
for (size_t ii = whitespace_position + 1U;
ii < line_size; ++ii) {
switch (line_buffer[ii]) {
case '=':
equals_position = ii;
goto found_equal;
case ' ':
case '\t':
break;
default:
err = LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
}
if (err != 0)
break;
}
if (err != 0)
break;
err = LNTD_ERROR_INVALID_PARAMETER;
state = PARSER_ERROR;
break;
found_equal:
;
size_t value_offset = equals_position + 1U;
size_t value_len = line_size - value_offset;
char *field;
{
void *xx;
err = lntd_mem_alloc(&xx, field_len + 1U);
if (err != 0) {
state = PARSER_ERROR;
break;
}
field = xx;
}
if (field_len > 0U)
memcpy(field, line_buffer, field_len);
field[field_len] = '\0';
char *value;
{
void *xx;
err = lntd_mem_alloc(&xx, value_len + 1U);
if (err != 0) {
lntd_mem_free(field);
state = PARSER_ERROR;
break;
}
value = xx;
}
memcpy(value, line_buffer + value_offset, value_len);
value[value_len] = '\0';
wordexp_t expr;
switch (wordexp(value, &expr, WRDE_NOCMD)) {
case WRDE_BADCHAR:
case WRDE_CMDSUB:
case WRDE_SYNTAX:
err = LNTD_ERROR_INVALID_PARAMETER;
break;
case WRDE_NOSPACE:
err = LNTD_ERROR_OUT_OF_MEMORY;
break;
}
lntd_mem_free(value);
if (err != 0) {
lntd_mem_free(field);
wordfree(&expr);
state = PARSER_ERROR;
break;
}
parser->field = field;
parser->expr = expr;
result->result_union.value.field = field;
result->result_union.value.value =
(char const *const *)expr.we_wordv;
state = PARSER_VALUE;
break;
}
}
set_values:
parser->line_buffer = line_buffer;
parser->line_capacity = line_capacity;
parser->state = state;
result->state = state;
return err;
}
static void section_init(struct conf_section *section)
{
section->buckets_used = 0U;
for (size_t jj = 0U; jj < SETTING_BUCKETS_SIZE; ++jj) {
struct conf_setting_bucket *bucket =
§ion->buckets[jj];
bucket->settings_size = 0U;
bucket->settings = 0;
}
}
static void section_free(struct conf_section *section)
{
struct conf_setting_bucket *buckets = section->buckets;
for (size_t kk = 0U; kk < SETTING_BUCKETS_SIZE; ++kk) {
struct conf_setting_bucket const *setting_bucket =
&buckets[kk];
size_t settings_size = setting_bucket->settings_size;
struct conf_setting *settings =
setting_bucket->settings;
free_settings(settings, settings_size);
lntd_mem_free(settings);
}
}
static char const *const *section_find(struct conf_section *section,
char const *field)
{
struct conf_setting_bucket *buckets = section->buckets;
struct conf_setting_bucket *bucket =
&buckets[string_hash(field) % SETTING_BUCKETS_SIZE];
size_t settings_size = bucket->settings_size;
struct conf_setting *settings = bucket->settings;
size_t setting_index;
bool have_found_setting = false;
for (size_t ii = 0U; ii < settings_size; ++ii) {
if (0 == strcmp(settings[ii].field, field)) {
have_found_setting = true;
setting_index = ii;
break;
}
}
if (!have_found_setting)
return 0;
return (char const *const *)settings[setting_index].value;
}
static lntd_error section_add(struct conf_section *section,
char const *field,
char const *const *additional_values)
{
lntd_error err;
struct conf_setting_bucket *buckets = section->buckets;
struct conf_setting_bucket *bucket =
&buckets[string_hash(field) % SETTING_BUCKETS_SIZE];
size_t settings_size = bucket->settings_size;
struct conf_setting *settings = bucket->settings;
size_t additional_values_len =
string_list_size(additional_values);
{
size_t found_field;
bool have_found_field = false;
for (size_t ii = 0U; ii < settings_size; ++ii) {
if (0 == strcmp(settings[ii].field, field)) {
found_field = ii;
have_found_field = true;
break;
}
}
if (!have_found_field)
goto have_not_found_field;
struct conf_setting *setting = &settings[found_field];
char *setting_field = setting->field;
char **setting_values = setting->value;
if (0U == additional_values_len) {
lntd_mem_free(setting_field);
for (size_t ii = 0U; setting_values[ii] != 0;
++ii)
lntd_mem_free(setting_values[ii]);
lntd_mem_free(setting_values);
bucket->settings_size = settings_size - 1U;
memcpy(bucket->settings + found_field,
buckets->settings + found_field + 1U,
(settings_size - 1U - found_field) *
sizeof bucket->settings[0U]);
} else {
size_t setting_values_len = string_list_size(
(char const *const *)setting_values);
size_t new_value_len =
setting_values_len + additional_values_len;
char **new_value;
{
void *xx;
err = lntd_mem_alloc_array(
&xx, new_value_len + 1U,
sizeof additional_values[0U]);
if (err != 0)
return err;
new_value = xx;
}
for (size_t ii = 0U; ii < setting_values_len;
++ii)
new_value[ii] = setting_values[ii];
for (size_t ii = 0U; ii < additional_values_len;
++ii) {
char *copy;
{
char *xx;
err = lntd_str_dup(
&xx, additional_values[ii]);
if (err != 0) {
for (; ii != 0; --ii)
lntd_mem_free(
new_value
[ii -
1U]);
lntd_mem_free(
new_value);
return err;
}
copy = xx;
}
new_value[setting_values_len + ii] =
copy;
}
new_value[new_value_len] = 0;
lntd_mem_free(setting_values);
setting->field = setting_field;
setting->value = new_value;
}
return 0;
}
have_not_found_field:
;
char *field_dup;
{
char *xx;
err = lntd_str_dup(&xx, field);
if (err != 0)
return err;
field_dup = xx;
}
char **value_copy;
{
void *xx;
err = lntd_mem_alloc_array(
&xx, additional_values_len + 1U,
sizeof additional_values[0U]);
if (err != 0)
goto free_field_dup;
value_copy = xx;
}
size_t values = 0U;
for (; values < additional_values_len; ++values) {
char *copy;
{
char *xx;
err = lntd_str_dup(&xx,
additional_values[values]);
if (err != 0)
goto free_value_copy;
copy = xx;
}
value_copy[values] = copy;
}
value_copy[additional_values_len] = 0;
size_t new_settings_size = settings_size + 1U;
struct conf_setting *new_settings;
{
void *xx;
err = lntd_mem_realloc_array(&xx, settings,
new_settings_size,
sizeof settings[0U]);
if (err != 0) {
for (size_t ii = 0U; value_copy[ii] != 0; ++ii)
lntd_mem_free(value_copy[ii]);
lntd_mem_free(value_copy);
return err;
}
new_settings = xx;
}
new_settings[settings_size].field = field_dup;
new_settings[settings_size].value = value_copy;
bucket->settings_size = new_settings_size;
bucket->settings = new_settings;
return 0;
free_value_copy:
for (size_t jj = 0U; jj < values; ++jj)
lntd_mem_free(value_copy[jj]);
lntd_mem_free(value_copy);
free_field_dup:
lntd_mem_free(field_dup);
return err;
}
static void free_settings(struct conf_setting *settings,
size_t settings_size)
{
for (size_t ww = 0U; ww < settings_size; ++ww) {
struct conf_setting *setting = &settings[ww];
lntd_mem_free(setting->field);
for (char **value = setting->value; *value != 0;
++value)
lntd_mem_free(*value);
lntd_mem_free(setting->value);
}
}
|
mstewartgallus/linted | src/window/window-posix.c | /*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include "lntd/window.h"
#include "lntd/error.h"
#include "lntd/io.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/rpc.h"
#include "lntd/util.h"
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <unistd.h>
lntd_error lntd_window_write(lntd_window window, uint_fast32_t in)
{
lntd_error err;
char buf[LNTD_RPC_UINT32_SIZE];
lntd_rpc_pack_uint32(in, buf);
/*
* From POSIX
*
* If write() is interrupted by a signal after it successfully
* writes some data, it shall return the number of bytes
* written.
*
* So, make writes atomic by preventing signals during the
* write.
*/
sigset_t oldset;
sigfillset(&oldset);
err = pthread_sigmask(SIG_BLOCK, &oldset, &oldset);
if (err != 0)
return err;
if (-1 == pwrite(window, buf, sizeof buf, 0U)) {
err = errno;
LNTD_ASSUME(err != 0);
}
lntd_error restore_err =
pthread_sigmask(SIG_SETMASK, &oldset, 0);
if (0 == err)
err = restore_err;
/*
* From POSIX
*
* Writes can be serialized with respect to other reads and
* writes. If a read() of file data can be proven (by any
* means) to occur after a write() of the data, it must
* reflect that write(), even if the calls are made by
* different processes. A similar requirement applies to
* multiple write operations to the same file position. This
* is needed to guarantee the propagation of data from write()
* calls to subsequent read() calls. This requirement is
* particularly significant for networked file systems, where
* some caching schemes violate these semantics.
*
* So, no fdatasync call needs to be made.
*/
return err;
}
lntd_error lntd_window_read(lntd_window window, uint_fast32_t *outp)
{
lntd_error err;
char buf[LNTD_RPC_UINT32_SIZE];
sigset_t oldset;
sigfillset(&oldset);
err = pthread_sigmask(SIG_BLOCK, &oldset, &oldset);
if (err != 0)
return err;
ssize_t bytes = pread(window, buf, sizeof buf, 0U);
if (-1 == bytes) {
err = errno;
LNTD_ASSUME(err != 0);
}
lntd_error restore_err =
pthread_sigmask(SIG_SETMASK, &oldset, 0);
if (0 == err)
err = restore_err;
if (err != 0)
return err;
if (bytes != sizeof buf)
return EPROTO;
*outp = lntd_rpc_unpack_uint32(buf);
return 0;
}
|
mstewartgallus/linted | src/signal/signal-posix.c | <gh_stars>0
/*
* Copyright 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include "config.h"
#include "lntd/signal.h"
#include "lntd/async.h"
#include "lntd/error.h"
#include "lntd/fifo.h"
#include "lntd/ko.h"
#include "lntd/mem.h"
#include "lntd/util.h"
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
enum { LNTD_SIGNAL_HUP,
LNTD_SIGNAL_CHLD,
LNTD_SIGNAL_INT,
LNTD_SIGNAL_TERM,
LNTD_SIGNAL_QUIT,
NUM_SIGS };
static lntd_ko sigpipe_reader = (lntd_ko)-1;
static lntd_ko sigpipe_writer = (lntd_ko)-1;
struct lntd_signal_task_wait {
struct lntd_async_task *parent;
struct lntd_async_waiter *waiter;
void *data;
int signo;
};
static void write_one(lntd_ko ko);
static void report_sigchld(int signo);
static void report_sighup(int signo);
static void report_sigint(int signo);
static void report_sigquit(int signo);
static void report_sigterm(int signo);
static atomic_bool sigchld_signalled;
static atomic_bool sighup_signalled;
static atomic_bool sigint_signalled;
static atomic_bool sigquit_signalled;
static atomic_bool sigterm_signalled;
static int const signals[NUM_SIGS] = {[LNTD_SIGNAL_HUP] = SIGHUP,
[LNTD_SIGNAL_CHLD] = SIGCHLD,
[LNTD_SIGNAL_INT] = SIGINT,
[LNTD_SIGNAL_QUIT] = SIGQUIT,
[LNTD_SIGNAL_TERM] = SIGTERM};
static void (*const sighandlers[NUM_SIGS])(
int) = {[LNTD_SIGNAL_HUP] = report_sighup,
[LNTD_SIGNAL_CHLD] = report_sigchld,
[LNTD_SIGNAL_INT] = report_sigint,
[LNTD_SIGNAL_QUIT] = report_sigquit,
[LNTD_SIGNAL_TERM] = report_sigterm};
static void *signal_routine(void *arg);
lntd_error lntd_signal_init(void)
{
lntd_error err = 0;
lntd_ko reader;
lntd_ko writer;
{
lntd_ko xx;
lntd_ko yy;
err = lntd_fifo_pair(&xx, &yy, 0);
if (err != 0)
return err;
reader = xx;
writer = yy;
}
sigpipe_reader = reader;
sigpipe_writer = writer;
{
sigset_t set;
sigemptyset(&set);
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(signals);
++ii) {
sigaddset(&set, signals[ii]);
}
err = pthread_sigmask(SIG_BLOCK, &set, 0);
if (err != 0)
goto close_fifos;
}
pthread_t xx;
err = pthread_create(&xx, 0, signal_routine, 0);
if (err != 0)
goto close_fifos;
return 0;
close_fifos:
lntd_ko_close(reader);
lntd_ko_close(writer);
return err;
}
lntd_error
lntd_signal_task_wait_create(struct lntd_signal_task_wait **taskp,
void *data)
{
lntd_error err;
struct lntd_signal_task_wait *task;
{
void *xx;
err = lntd_mem_alloc(&xx, sizeof *task);
if (err != 0)
return err;
task = xx;
}
struct lntd_async_task *parent;
{
struct lntd_async_task *xx;
err = lntd_async_task_create(
&xx, task, LNTD_ASYNCH_TASK_SIGNAL_WAIT);
if (err != 0)
goto free_task;
parent = xx;
}
struct lntd_async_waiter *waiter;
{
struct lntd_async_waiter *xx;
err = lntd_async_waiter_create(&xx);
if (err != 0)
goto free_parent;
waiter = xx;
}
task->waiter = waiter;
task->parent = parent;
task->data = data;
*taskp = task;
return 0;
free_parent:
lntd_async_task_destroy(parent);
free_task:
lntd_mem_free(task);
return err;
}
void lntd_signal_task_wait_destroy(struct lntd_signal_task_wait *task)
{
lntd_async_waiter_destroy(task->waiter);
lntd_async_task_destroy(task->parent);
lntd_mem_free(task);
}
void *lntd_signal_task_wait_data(struct lntd_signal_task_wait *task)
{
return task->data;
}
int lntd_signal_task_wait_signo(struct lntd_signal_task_wait *task)
{
return task->signo;
}
void lntd_signal_task_wait_cancel(struct lntd_signal_task_wait *task)
{
lntd_async_task_cancel(task->parent);
}
void lntd_signal_task_wait_submit(struct lntd_async_pool *pool,
struct lntd_signal_task_wait *task,
union lntd_async_ck task_ck,
void *userstate)
{
lntd_async_task_submit(pool, task->parent, task_ck, userstate);
}
void lntd_signal_do_wait(struct lntd_async_pool *pool,
struct lntd_async_task *task)
{
struct lntd_signal_task_wait *task_wait =
lntd_async_task_data(task);
lntd_error err = 0;
struct lntd_async_waiter *waiter = task_wait->waiter;
int signo = -1;
for (;;) {
static char dummy;
if (-1 == read(sigpipe_reader, &dummy, sizeof dummy)) {
err = errno;
LNTD_ASSUME(err != 0);
if (EAGAIN == err)
break;
if (EINTR == err)
goto resubmit;
goto complete;
}
}
err = 0;
if (atomic_fetch_and_explicit(&sighup_signalled, 0,
memory_order_seq_cst)) {
signo = SIGHUP;
goto complete;
}
if (atomic_fetch_and_explicit(&sigchld_signalled, 0,
memory_order_seq_cst)) {
signo = SIGCHLD;
goto complete;
}
if (atomic_fetch_and_explicit(&sigint_signalled, 0,
memory_order_seq_cst)) {
signo = SIGINT;
goto complete;
}
if (atomic_fetch_and_explicit(&sigquit_signalled, 0,
memory_order_seq_cst)) {
signo = SIGQUIT;
goto complete;
}
if (atomic_fetch_and_explicit(&sigterm_signalled, 0,
memory_order_seq_cst)) {
signo = SIGTERM;
goto complete;
}
goto wait_on_poll;
complete:
task_wait->signo = signo;
if (0 == err) {
write_one(sigpipe_writer);
}
lntd_async_pool_complete(pool, task, err);
return;
resubmit:
lntd_async_pool_resubmit(pool, task);
return;
wait_on_poll:
lntd_async_pool_wait_on_poll(pool, waiter, task, sigpipe_reader,
POLLIN);
}
#if defined __GLIBC__
char const *lntd_signal_string(int signo)
{
/* GLibc's strsignal can allocate memory on unknown values
* which is wrong and bad. */
static char const unknown_signal[] = "Unknown signal";
if (signo >= NSIG)
return unknown_signal;
if (signo <= 0)
return unknown_signal;
return strsignal(signo);
}
#else
char const *lntd_signal_string(int signo)
{
return strsignal(signo);
}
#endif
static void listen_to_signal(size_t ii);
void lntd_signal_listen_to_sigchld(void)
{
listen_to_signal(LNTD_SIGNAL_CHLD);
}
void lntd_signal_listen_to_sighup(void)
{
listen_to_signal(LNTD_SIGNAL_HUP);
}
void lntd_signal_listen_to_sigint(void)
{
listen_to_signal(LNTD_SIGNAL_INT);
}
void lntd_signal_listen_to_sigquit(void)
{
listen_to_signal(LNTD_SIGNAL_QUIT);
}
void lntd_signal_listen_to_sigterm(void)
{
listen_to_signal(LNTD_SIGNAL_TERM);
}
static void *signal_routine(void *arg)
{
{
sigset_t set;
sigemptyset(&set);
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(signals);
++ii) {
sigaddset(&set, signals[ii]);
}
lntd_error err = pthread_sigmask(SIG_UNBLOCK, &set, 0);
LNTD_ASSERT(0 == err);
}
for (;;)
pause();
}
static void listen_to_signal(size_t n)
{
lntd_error err;
int signo = signals[n];
void (*handler)(int) = sighandlers[n];
struct sigaction action = {0};
action.sa_handler = handler;
action.sa_flags = 0;
/*
* We cannot block all signals as that may lead to bad
* situations when things like stack overflows happen.
*/
sigemptyset(&action.sa_mask);
/* Block SIGPIPEs to get EPIPEs */
sigaddset(&action.sa_mask, SIGPIPE);
/* Block the other kill signals for less unpredictability */
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(signals); ++ii) {
sigaddset(&action.sa_mask, signals[ii]);
}
if (-1 == sigaction(signo, &action, 0)) {
err = errno;
LNTD_ASSUME(err != 0);
LNTD_ASSERT(false);
}
}
static void report_sigchld(int signo)
{
lntd_error err = errno;
atomic_store_explicit(&sigchld_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
errno = err;
}
static void report_sighup(int signo)
{
lntd_error err = errno;
atomic_store_explicit(&sighup_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
errno = err;
}
static void report_sigint(int signo)
{
lntd_error err = errno;
atomic_store_explicit(&sigint_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
errno = err;
}
static void report_sigquit(int signo)
{
lntd_error err = errno;
atomic_store_explicit(&sigquit_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
errno = err;
}
static void report_sigterm(int signo)
{
lntd_error err = errno;
atomic_store_explicit(&sigterm_signalled, 1,
memory_order_seq_cst);
write_one(sigpipe_writer);
errno = err;
}
static void write_one(lntd_ko ko)
{
lntd_error err = 0;
static char const dummy;
for (;;) {
ssize_t result = write(ko, &dummy, 1U);
if (-1 == result) {
err = errno;
LNTD_ASSUME(err != 0);
}
if (0 == result)
continue;
if (err != EINTR)
break;
}
/* EAGAIN and EWOULDBLOCK are okay, they mean the pipe is full
* and that's fine.
*/
if (EAGAIN == err)
err = 0;
if (EWOULDBLOCK == err)
err = 0;
LNTD_ASSERT(err != EBADF);
LNTD_ASSERT(err != EDESTADDRREQ);
LNTD_ASSERT(err != EDQUOT);
LNTD_ASSERT(err != EFAULT);
LNTD_ASSERT(err != EFBIG);
LNTD_ASSERT(err != EINVAL);
LNTD_ASSERT(err != EIO);
LNTD_ASSERT(err != ENOSPC);
/* EPIPE should never happen because SIGPIPE is blocked */
LNTD_ASSERT(err != EPIPE);
LNTD_ASSERT(0 == err);
}
|
mstewartgallus/linted | src/start/start-windows.c | <filename>src/start/start-windows.c<gh_stars>0
/*
* Copyright 2013, 2014, 2015 <NAME>
*
* Licensed 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef UNICODE
#define UNICODE
#endif
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#define LNTD_START__NO_MAIN 1
#include "lntd/start.h"
#include "lntd/async.h"
#include "lntd/env.h"
#include "lntd/log.h"
#include "lntd/mem.h"
#include "lntd/path.h"
#include "lntd/signal.h"
#include "lntd/str.h"
#include "lntd/utf.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <shellapi.h>
#include <winsock2.h>
/**
* @file
*
* @todo Windows: open standard handles if they are closed
* (`GetStdHandle` returns a null pointer.)
*/
static int show_command;
lntd_error privilege_check(void);
int lntd_start_show_command(void)
{
return show_command;
}
int lntd_start__main(struct lntd_start_config const *config,
char const **_process_namep, size_t *_argcp,
char const *const **_argvp)
{
/* Cannot fail, return value is only the previous state */
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX |
SEM_NOGPFAULTERRORBOX);
/* Prevent dynamic DLL Loading from loading from the current
* directory */
if (!SetDllDirectoryW(L""))
return EXIT_FAILURE;
{
STARTUPINFO info = {0};
GetStartupInfo(&info);
show_command =
(info.dwFlags & STARTF_USESHOWWINDOW) != 0
? info.wShowWindow
: SW_SHOWDEFAULT;
}
lntd_error err;
wchar_t *raw_command_line = GetCommandLineW();
wchar_t **wide_argv;
size_t argc;
{
int xx;
wide_argv = CommandLineToArgvW(raw_command_line, &xx);
if (0 == wide_argv)
return EXIT_FAILURE;
argc = xx;
}
char **argv;
{
void *xx;
err = lntd_mem_alloc_array(&xx, argc + 1U,
sizeof argv[0U]);
if (err != 0)
return EXIT_FAILURE;
argv = xx;
}
for (size_t ii = 0U; ii < argc; ++ii) {
err = lntd_utf_2_to_1(wide_argv[ii], &argv[ii]);
if (err != 0)
return EXIT_FAILURE;
}
LocalFree(wide_argv);
char const *process_name = 0;
bool missing_name = false;
char const *service;
{
char *xx;
err = lntd_env_get("LINTED_SERVICE", &xx);
if (err != 0)
return EXIT_FAILURE;
service = xx;
}
if (service != 0) {
process_name = service;
} else if (argc > 0) {
process_name = argv[0U];
} else {
process_name = config->canonical_process_name;
missing_name = true;
}
char *process_basename;
{
char *xx;
err = lntd_path_base(&xx, process_name);
if (err != 0)
return EXIT_FAILURE;
process_basename = xx;
}
lntd_log_open(process_basename);
if (missing_name) {
lntd_log(LNTD_LOG_ERROR, "missing process name");
return EXIT_FAILURE;
}
if (config->check_privilege) {
err = privilege_check();
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "privilege_check: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
if (!config->dont_init_signals) {
err = lntd_signal_init();
if (err != 0) {
lntd_log(LNTD_LOG_ERROR, "lntd_signal_init: %s",
lntd_error_string(err));
return EXIT_FAILURE;
}
}
int error_code;
{
WSADATA xx;
error_code = WSAStartup(MAKEWORD(2, 2), &xx);
}
if (error_code != 0) {
lntd_log(LNTD_LOG_ERROR, "WSAStartup: %s",
lntd_error_string(error_code));
return EXIT_FAILURE;
}
*_process_namep = process_basename;
*_argcp = argc;
*_argvp = (char const *const *)argv;
return EXIT_SUCCESS;
}
/*
* The following count as enabled under Wine. I should learn how to
* create a restricted account under Wine and then check for these.
*
* SE_CHANGE_NOTIFY_NAME
* SE_CREATE_GLOBAL_NAME
* SE_IMPERSONATE_NAME
* SE_LOAD_DRIVER_NAME
*
* The following aren't found under Wine. I should probably just
* handle not found permissions by ignoring them.
*
* SE_CREATE_SYMBOLIC_LINK_NAME
* SE_INC_WORKING_SET_NAME
* SE_RELABEL_NAME
* SE_TIME_ZONE_NAME
* SE_TRUSTED_CREDMAN_ACCESS_NAME
* SE_UNSOLICITED_INPUT_NAME
*/
static wchar_t const *const access_names[] = {
SE_ASSIGNPRIMARYTOKEN_NAME, /**/
SE_ASSIGNPRIMARYTOKEN_NAME, /**/
SE_AUDIT_NAME, /**/
SE_BACKUP_NAME, /**/
SE_CREATE_PAGEFILE_NAME, /**/
SE_CREATE_PERMANENT_NAME, /**/
SE_CREATE_TOKEN_NAME, /**/
SE_DEBUG_NAME, /**/
SE_ENABLE_DELEGATION_NAME, /**/
SE_INC_BASE_PRIORITY_NAME, /**/
SE_INCREASE_QUOTA_NAME, /**/
SE_LOCK_MEMORY_NAME, /**/
SE_MACHINE_ACCOUNT_NAME, /**/
SE_MANAGE_VOLUME_NAME, /**/
SE_PROF_SINGLE_PROCESS_NAME, /**/
SE_RESTORE_NAME, /**/
SE_SECURITY_NAME, /**/
SE_SHUTDOWN_NAME, /**/
SE_SYNC_AGENT_NAME, /**/
SE_SYSTEM_ENVIRONMENT_NAME, /**/
SE_SYSTEM_PROFILE_NAME, /**/
SE_SYSTEMTIME_NAME, /**/
SE_TAKE_OWNERSHIP_NAME, /**/
SE_TCB_NAME, /**/
SE_UNDOCK_NAME};
lntd_error privilege_check(void)
{
lntd_error err = 0;
struct {
DWORD PrivilegeCount;
DWORD Control;
LUID_AND_ATTRIBUTES
Privilege[LNTD_ARRAY_SIZE(access_names)];
} privileges = {0};
privileges.PrivilegeCount = LNTD_ARRAY_SIZE(access_names);
privileges.Control = 0;
for (size_t ii = 0U; ii < LNTD_ARRAY_SIZE(access_names); ++ii) {
LUID xx;
if (!LookupPrivilegeValue(0, access_names[ii], &xx)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
privileges.Privilege[ii].Luid = xx;
privileges.Privilege[ii].Attributes =
SE_PRIVILEGE_ENABLED;
}
HANDLE current_process_access_token;
{
HANDLE xx;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY,
&xx)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
return err;
}
current_process_access_token = xx;
}
BOOL result;
if (!PrivilegeCheck(current_process_access_token,
(void *)&privileges, &result)) {
err = HRESULT_FROM_WIN32(GetLastError());
LNTD_ASSUME(err != 0);
}
CloseHandle(current_process_access_token);
if (err != 0)
return err;
if (result)
return LNTD_ERROR_PERMISSION;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.