unsafe -is:module

Unified interface to unsafe functions SafeHaskell introduced the notion of safe and unsafe modules. In order to make as many as possible modules "safe", the well-known unsafe functions were moved to distinguished modules. This makes it hard to write packages that work with both old and new versions of GHC. This package provides a single module System.Unsafe that exports the unsafe functions from the base package. It provides them in a style ready for qualification, that is, you should import them by
import qualified System.Unsafe as Unsafe
The package also contains a script called rename-unsafe.sh. It replaces all occurrences of the original identifiers with the qualified identifiers from this package. You still have to adapt the import commands. It uses the darcs-replace-rec script from the darcs-scripts package.
Compile a module in the Unsafe, Safe Haskell mode so that modules compiled using Safe, Safe Haskell mode can't import it.
unsafeDupableInterleaveST allows an ST computation to be deferred lazily. When passed a value of type ST a, the ST computation will only be performed when the value of the a is demanded. The computation may be performed multiple times by different threads, possibly at the same time. To prevent this, use unsafeInterleaveST instead.
Convert an IO action to an ST action. This relies on IO and ST having the same representation modulo the constraint on the state thread type parameter.
unsafeInterleaveST allows an ST computation to be deferred lazily. When passed a value of type ST a, the ST computation will only be performed when the value of the a is demanded.
Convert an ST action to an IO action. This relies on IO and ST having the same representation modulo the constraint on the state thread type parameter. For an example demonstrating why this is unsafe, see https://mail.haskell.org/pipermail/haskell-cafe/2009-April/060719.html
Shift the argument left by the specified number of bits. The result is undefined for negative shift amounts and shift amounts greater or equal to the bitSize. Defaults to shiftL unless defined explicitly by an instance.
Shift the first argument right by the specified number of bits, which must be non-negative and smaller than the number of bits in the type. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the x is negative and with 0 otherwise. Defaults to shiftR unless defined explicitly by an instance.
This function extracts the pointer component of a foreign pointer. This is a potentially dangerous operations, as if the argument to unsafeForeignPtrToPtr is the last usage occurrence of the given foreign pointer, then its finalizer(s) will be run, which potentially invalidates the plain pointer just obtained. Hence, touchForeignPtr must be used wherever it has to be guaranteed that the pointer lives on - i.e., has another usage occurrence. To avoid subtle coding errors, hand written marshalling code should preferably use withForeignPtr rather than combinations of unsafeForeignPtrToPtr and touchForeignPtr. However, the latter routines are occasionally preferred in tool generated marshalling code.
Sometimes an external entity is a pure function, except that it passes arguments and/or results via pointers. The function unsafeLocalState permits the packaging of such entities as pure functions. The only IO operations allowed in the IO action passed to unsafeLocalState are (a) local allocation (alloca, allocaBytes and derived operations such as withArray and withCString), and (b) pointer operations (Foreign.Storable and Foreign.Ptr) on the pointers to local storage, and (c) foreign functions whose only observable effect is to read and/or write the locally allocated memory. Passing an IO operation that does not obey these rules results in undefined behaviour. It is expected that this operation will be replaced in a future revision of Haskell.
This version of unsafePerformIO is more efficient because it omits the check that the IO is only being performed by a single thread. Hence, when you use unsafeDupablePerformIO, there is a possibility that the IO action may be performed multiple times (on a multiprocessor), and you should therefore ensure that it gives the same results each time. It may even happen that one of the duplicated IO actions is only run partially, and then interrupted in the middle without an exception being raised. Therefore, functions like bracket cannot be used safely within unsafeDupablePerformIO.
A slightly faster version of fixIO that may not be safe to use with multiple threads. The unsafety arises when used like this:
unsafeFixIO $ \r -> do
forkIO (print r)
return (...)
In this case, the child thread will receive a NonTermination exception instead of waiting for the value of r to be computed.
unsafeInterleaveIO allows an IO computation to be deferred lazily. When passed a value of type IO a, the IO will only be performed when the value of the a is demanded. This is used to implement lazy file reading, see hGetContents.
This is the "back door" into the IO monad, allowing IO computation to be performed at any time. For this to be safe, the IO computation should be free of side effects and independent of its environment. If the I/O computation wrapped in unsafePerformIO performs side effects, then the relative order in which those side effects take place (relative to the main I/O trunk, or other calls to unsafePerformIO) is indeterminate. Furthermore, when using unsafePerformIO to cause side-effects, you should take the following precautions to ensure the side effects are performed as many times as you expect them to be. Note that these precautions are necessary for GHC, but may not be sufficient, and other compilers may require different precautions:
  • Use {-# NOINLINE foo #-} as a pragma on any function foo that calls unsafePerformIO. If the call is inlined, the I/O may be performed more than once.
  • Use the compiler flag -fno-cse to prevent common sub-expression elimination being performed on the module, which might combine two side effects that were meant to be separate. A good example is using multiple global variables (like test in the example below).
  • Make sure that the either you switch off let-floating (-fno-full-laziness), or that the call to unsafePerformIO cannot float outside a lambda. For example, if you say: f x = unsafePerformIO (newIORef []) you may get only one reference cell shared between all calls to f. Better would be f x = unsafePerformIO (newIORef [x]) because now it can't float outside the lambda.
It is less well known that unsafePerformIO is not type safe. For example:
test :: IORef [a]
test = unsafePerformIO $ newIORef []

main = do
writeIORef test [42]
bang <- readIORef test
print (bang :: [Char])
This program will core dump. This problem with polymorphic references is well known in the ML community, and does not arise with normal monadic use of references. There is no easy way to make it impossible once you use unsafePerformIO. Indeed, it is possible to write coerce :: a -> b with the help of unsafePerformIO. So be careful! WARNING: If you're looking for "a way to get a String from an 'IO String'", then unsafePerformIO is not the way to go. Learn about do-notation and the <- syntax element before you proceed.
unsafeCoerce coerces a value from one type to another, bypassing the type-checker. There are several legitimate ways to use unsafeCoerce:
  1. To coerce a lifted type such as Int to Any, put it in a list of Any, and then later coerce it back to Int before using it.
  2. To produce e.g. (a+b) :~: (b+a) from unsafeCoerce Refl. Here the two sides really are the same type -- so nothing unsafe is happening -- but GHC is not clever enough to see it.
  3. In Data.Typeable we have
eqTypeRep :: forall k1 k2 (a :: k1) (b :: k2).
TypeRep a -> TypeRep b -> Maybe (a :~~: b)
eqTypeRep a b
| sameTypeRep a b = Just (unsafeCoerce HRefl)
| otherwise       = Nothing

Here again, the unsafeCoerce HRefl is safe, because the two types really are the same -- but the proof of that relies on the complex, trusted implementation of Typeable.
  1. (superseded) The "reflection trick", which takes advantage of the fact that in class C a where { op :: ty }, we can safely coerce between C a and ty (which have different kinds!) because it's really just a newtype. Note: there is no guarantee, at all that this behavior will be supported into perpetuity. It is now preferred to use withDict in GHC.Magic.Dict, which is type-safe. See Note [withDict] in GHC.Tc.Instance.Class for details.
  2. (superseded) Casting between two types which have exactly the same structure: between a newtype of T and T, or between types which differ only in "phantom" type parameters. It is now preferred to use coerce from Data.Coerce, which is type-safe.
Other uses of unsafeCoerce are undefined. In particular, you should not use unsafeCoerce to cast a T to an algebraic data type D, unless T is also an algebraic data type. For example, do not cast Int->Int to Bool, even if you later cast that Bool back to Int->Int before applying it. The reasons have to do with GHC's internal representation details (for the cognoscenti, data values can be entered but function closures cannot). If you want a safe type to cast things to, use Any, which is not an algebraic data type.
Highly, terribly dangerous coercion from one representation type to another. Misuse of this function can invite the garbage collector to trounce upon your data and then laugh in your face. You don't want this function. Really. This becomes more obvious when looking at its actual type: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep) (a :: TYPE r1) (b :: TYPE r2). a -> b Which often get's rendered as a -> b in haddock for technical reasons.